// Written by Paul Clevett // (C)Copyright IntelligentWolf Ltd // https://wolf.uk.com //! REST API for WolfStack dashboard and agent communication use actix_web::{web, HttpResponse, HttpRequest, cookie::Cookie}; use serde::{Deserialize, Serialize}; use std::sync::Arc; use std::process::Command; use tracing::{warn, error}; use crate::monitoring::{SystemMonitor, MetricsHistory}; use crate::installer; use crate::containers; use crate::storage; use crate::networking; use crate::backup; use crate::agent::ClusterState; use crate::auth::SessionManager; use crate::appstore; use crate::node_identity::PeerAuth; pub mod pve_console; pub mod container_vnc; mod cluster_browser_proxy; /// Shared HTTP client for every cluster-peer / external / self-loop /// call in this file. Previously ~40 API handlers each built their /// own `reqwest::Client::builder()...build()`, leaking a connection /// pool per handler invocation. Timeouts are set per-request via /// `RequestBuilder::timeout` because each call site uses a different /// deadline (3s health-check through 600s VM migration). A 3s /// `connect_timeout` at Client level makes dead peers fail fast /// without burning the full per-request budget on TCP handshake. pub(crate) static API_HTTP_CLIENT: std::sync::LazyLock = std::sync::LazyLock::new(|| { ipv4_only_client_builder() .connect_timeout(std::time::Duration::from_secs(3)) .danger_accept_invalid_certs(true) // Aggressively trim the idle-connection pool so orphaned // sockets don't sit in CLOSE_WAIT for 90s (the default). // Reported by Bel: 5827 outbound CLOSE_WAIT against peer // :8553 endpoints built up alongside server-side leaks. .pool_idle_timeout(std::time::Duration::from_secs(15)) .pool_max_idle_per_host(8) // Enable SO_KEEPALIVE so half-dead connections are // detected and torn down by the kernel rather than // lingering for minutes. .tcp_keepalive(std::time::Duration::from_secs(30)) .build() .unwrap_or_else(|_| reqwest::Client::new()) }); /// DNS resolver that discards AAAA results and returns only IPv4 addresses. /// /// Wolfstacks run on mixed-stack hosts where AAAA records exist but the /// peer's :8553 is only bound to 0.0.0.0. Without filtering, hyper tries /// the v6 address first, times out, and only then falls back to v4. /// /// This replaces a previous `local_address(Ipv4Addr::UNSPECIFIED)`, which /// achieved the same filtering only as a *side effect* of setting a source /// address (hyper-util `SocketAddrs::split_by_preference`, /// client/legacy/connect/dns.rs:216-218, keeps only v4 candidates when /// `local_address_ipv4` is `Some`). The cost of that side effect is a /// `bind()` on every outbound connection: hyper-util `bind_local_address` /// (client/legacy/connect/http.rs:800-803) binds the socket to /// `:0` whenever a source address is set. Port 0 sends the kernel /// into `inet_csk_find_open_port`, which scans the bind table under a /// spinlock — cost proportional to the number of sockets on the host. /// /// On klas's node (2026-08-13) that scan was **77.7% of all CPU**, spread /// across 14 actix workers colliding in `native_queued_spin_lock_slowpath`, /// with 15,296 sockets in the table. Resolving the address family here /// keeps the behaviour and removes the syscall entirely — with no source /// address set, `bind_local_address`'s fallback arm is a no-op off Windows. struct Ipv4OnlyResolver; impl reqwest::dns::Resolve for Ipv4OnlyResolver { fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { Box::pin(async move { let host = name.as_str().to_owned(); // Port 0 is a placeholder — reqwest substitutes the scheme's // port. Documented on `Resolve::resolve`, reqwest-0.12.28 // src/dns/resolve.rs:30-31. let resolved = tokio::net::lookup_host((host.as_str(), 0)).await?; let v4: Vec = resolved.filter(std::net::SocketAddr::is_ipv4).collect(); Ok(Box::new(v4.into_iter()) as reqwest::dns::Addrs) }) } } /// Start a reqwest ClientBuilder pinned to IPv4, with safe pool and /// connect defaults for every caller. /// /// Hosts reached by IP literal never enter the resolver at all, so the /// v4 filtering costs nothing on the cluster-peer path; it exists for /// the hostname callers (registries, webhooks, licensing). pub(crate) fn ipv4_only_client_builder() -> reqwest::ClientBuilder { reqwest::Client::builder() .dns_resolver(std::sync::Arc::new(Ipv4OnlyResolver)) // DELIBERATELY NOT BOUNDING THE IDLE POOL HERE. Read this before // "fixing" the unbounded default — it has already cost a user two // dead nodes. // // v25.12.3 set `pool_max_idle_per_host(8)` and // `pool_idle_timeout(15s)`, reasoning that reqwest's `usize::MAX` // default lets request concurrency become a permanent socket // population. That reasoning is sound in isolation and the change // was catastrophic in practice. // // Once the pool holds its cap of idle connections for a peer, every // further returned connection is dropped at once, and a shorter idle // timeout reaps the rest six times more often. Both mean the CLIENT // closes first. WolfStack's own server has a separate, older bug // where an inbound connection is not closed after the peer's FIN, so // each of those closes becomes a permanent CLOSE-WAIT on the peer. // // Measured on one user's node, same machine, same cluster, across // the upgrade: inbound CLOSE-WAIT grew at 2.3/min on v25.12.2 and // 326/min on v25.12.3 — 140x — and took the node from "degraded" to // "exhausts 65,535 descriptors and stops accepting connections". // // Bounding the pool is only safe once the server closes its side // properly. Until then a bound just converts a slow leak into a // fast one. See tests/resource_safety.rs. // // SAFE DEFAULT for every client built through this factory. // // A total `.timeout()` does not bound a connection that never // establishes: a SYN to an unroutable address holds a descriptor for // the kernel's full retry window (~130s at tcp_syn_retries=6). Any // caller on a timer then stacks those until the fd table is gone — // the 2026-08-05 fleet outage (2,422 SYN-SENT, 2,868 CLOSE-WAIT, // ~700 sockets/min across twelve nodes). // // Callers that need a tighter bound override it; a looser one is // almost never right. Enforced by tests/resource_safety.rs. .connect_timeout(std::time::Duration::from_secs(5)) } /// Drain a response body before discarding so the socket returns to /// the keep-alive pool. Used by handlers that only care about /// `.status()` and would otherwise drop the Response unread. async fn drain_response(resp: reqwest::Response) { let _ = resp.bytes().await; } /// Build ordered URLs to try for inter-node communication. /// Check if an address is blocked for SSRF prevention (loopback, link-local, localhost) fn is_ssrf_blocked_address(addr: &str) -> bool { use std::net::IpAddr; // URL hosts carry IPv6 literals in brackets — strip them so the // parse below sees the bare address ("[::1]" must not slip past). let bare = addr.strip_prefix('[').and_then(|a| a.strip_suffix(']')).unwrap_or(addr); // Only block if it parses as a bare IP — hostnames are legitimate if let Ok(ip) = bare.parse::() { return ip.is_loopback() || matches!(ip, IpAddr::V4(a) if a.octets()[0] == 169 && a.octets()[1] == 254) // RFC 4291: fe80::/10 is IPv6 link-local — same class of // target as v4 169.254.0.0/16 above. || matches!(ip, IpAddr::V6(a) if (a.segments()[0] & 0xffc0) == 0xfe80); } // Reject "localhost" by name too addr.eq_ignore_ascii_case("localhost") } /// Address-keyed cache of each peer's host WolfNet IP. Populated from /// StatusReport (`wolfnet_ips[0]` is the host's own WolfNet address). /// Read by `build_node_urls` to insert a WolfNet-routed HTTP attempt /// between the HTTPS and the plain-HTTP fallbacks — encrypted at the /// WolfNet overlay layer instead of riding plaintext across the LAN. /// /// Empty until the first peer reports — in that window `build_node_urls` /// behaves identically to the pre-v20.9.9 3-URL chain. Stale entries are /// harmless: a fail on the WolfNet URL falls through to the existing /// HTTP fallbacks. static NODE_WOLFNET_IPS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); /// Record the given peer's host WolfNet IP. Called from agent::poll_peers /// when a StatusReport comes back. Empty `wolfnet_ip` clears the entry. pub fn record_node_wolfnet_ip(address: &str, wolfnet_ip: &str) { if let Ok(mut map) = NODE_WOLFNET_IPS.lock() { if wolfnet_ip.is_empty() { map.remove(address); } else { map.insert(address.to_string(), wolfnet_ip.to_string()); } } } pub fn lookup_node_wolfnet_ip(address: &str) -> Option { NODE_WOLFNET_IPS.lock().ok().and_then(|m| m.get(address).cloned()) } /// Reverse of `lookup_node_wolfnet_ip`: the node address that owns a /// WolfNet IP, so a request sent over the WolfNet fallback URL can still /// be signed for the right destination node. pub fn lookup_address_by_wolfnet_ip(wolfnet_ip: &str) -> Option { NODE_WOLFNET_IPS.lock().ok().and_then(|m| m.iter().find(|(_, v)| v.as_str() == wolfnet_ip).map(|(k, _)| k.clone())) } /// Build the URLs to try for an inter-node API call, in preference order: /// 1. HTTPS on the main port (TLS — secure; outbound clients all use /// `danger_accept_invalid_certs(true)` so self-signed peers work too) /// 2. HTTP on the peer's WolfNet IP, internal port (encrypted at L3 by /// the WolfNet overlay; only works if the peer is self-signed and /// therefore still binds the second listener, AND we've seen its /// WolfNet IP via a StatusReport) /// 3. HTTP on the main address, main port (plain — last resort, only /// succeeds against genuinely-HTTP-only peers, i.e. pre-v23.11 /// installs running with `--no-tls`) /// /// v23.12 removed the `http://address:port+1` step. CA-signed-cert peers /// no longer bind the second listener at all (Frigate clash avoidance); /// HTTPS-with-cert-bypass on the main port reaches every TLS peer including /// those still on a self-signed cert. pub fn build_node_urls(address: &str, port: u16, path: &str) -> Vec { // Bracket bare IPv6 literals — node addresses are stored bare; a raw // v6 literal in `host:port` makes the port colon ambiguous. v4 and // hostnames pass through unchanged. WolfNet IPs are v4 by design. let host = crate::netaddr::bracket_host(address); let mut urls = Vec::with_capacity(3); urls.push(format!("https://{}:{}{}", host, port, path)); if let Some(wn) = lookup_node_wolfnet_ip(address) { urls.push(format!("http://{}:{}{}", wn, port + 1, path)); } urls.push(format!("http://{}:{}{}", host, port, path)); urls } /// Extract the bare host from a target that may be `host`, `host:port`, or /// `scheme://host:port/path` (bracketed IPv6 supported). Mirrors the host /// parsing in `build_external_urls`. fn extract_target_host(target: &str) -> String { let trimmed = target.trim().trim_end_matches('/'); let after_scheme = match trimmed.find("://") { Some(i) => &trimmed[i + 3..], None => trimmed, }; let host_port = after_scheme.split('/').next().unwrap_or(after_scheme); if let Some(rest) = host_port.strip_prefix('[') { return rest.split(']').next().unwrap_or(rest).to_string(); } match host_port.rfind(':') { Some(pos) if !host_port[..pos].contains(':') => host_port[..pos].to_string(), _ => host_port.to_string(), } } /// True only if `target` names a host that is a REGISTERED member of this /// cluster. Our `X-WolfStack-Secret` is the fleet-root credential, so it must /// never be attached to an outbound request whose host isn't a cluster node — /// otherwise an operator- or attacker-supplied URL could capture the secret. /// Cross-cluster targets legitimately use a different secret and never needed /// ours, so gating this way loses no working behaviour. fn target_is_cluster_node(state: &AppState, target: &str) -> bool { let host = extract_target_host(target).to_ascii_lowercase(); if host.is_empty() { return false; } state.cluster.get_all_nodes().iter().any(|n| { let na = extract_target_host(&n.address).to_ascii_lowercase(); !na.is_empty() && na == host }) } /// Build ordered URLs to try for external (cross-cluster) communication. /// All destination nodes run WolfStack (HTTPS 8553, HTTP 8554), so we try those ports /// automatically — the user only needs to provide the hostname. pub fn build_external_urls(target_url: &str, path: &str) -> Vec { let trimmed = target_url.trim_end_matches('/'); // Ensure we have a scheme — prepend https:// if missing let with_scheme = if trimmed.contains("://") { trimmed.to_string() } else { format!("https://{}", trimmed) }; // Extract host from URL (scheme://host:port/path → host). A // bracketed IPv6 host ("[2001:db8::1]:8553") splits on the colon // AFTER the closing bracket. A bare IPv6 literal must NOT split at // all — its last group usually parses as a u16 ("::1" → port 1, // host ":"), which both mangles the host and slips it past the // SSRF guard below. Unbracketed-colon-in-head = bare v6 literal. let after_scheme = &with_scheme[with_scheme.find("://").unwrap() + 3..]; let host_port = after_scheme.split('/').next().unwrap_or(after_scheme); let (host, user_port) = match host_port.rfind(':') { Some(pos) if !host_port[pos..].contains(']') => { let head = &host_port[..pos]; if head.contains(':') && !head.ends_with(']') { (host_port, None) } else { let port_str = &host_port[pos + 1..]; match port_str.parse::() { Ok(port) => (head, Some(port)), Err(_) => (host_port, None), } } } _ => (host_port, None), }; // SSRF prevention: block loopback and link-local addresses if is_ssrf_blocked_address(host) { return Vec::new(); } let mut urls = Vec::new(); // If user specified a port, try their exact URL first if user_port.is_some() { urls.push(format!("{}{}", with_scheme, path)); } // Always try WolfStack's main HTTPS port. The old code also tried // http://host:8554 (legacy inter-node), but v23.12 dropped the // second listener for CA-signed-cert peers — and HTTPS-with-cert- // bypass already reaches self-signed peers via the main port, so // the 8554 attempt was always redundant when the main port is // reachable. Cross-cluster operators wanting plain HTTP can still // pass an explicit `http://host:port` URL — that's why we try the // user-supplied URL first above. if user_port != Some(8553) { urls.push(format!("https://{}:8553{}", crate::netaddr::bracket_host(host), path)); } urls } /// Progress state for PBS restore operations #[derive(Clone, Serialize, Default)] pub struct PbsRestoreProgress { pub active: bool, pub snapshot: String, pub progress_text: String, pub percentage: Option, pub finished: bool, pub success: Option, pub message: String, #[serde(skip)] pub started_at: Option, } /// Shared application state pub struct AppState { /// `Arc>` so the predictive orchestrator can clone a /// reference and call `collect()` on its own cadence without /// blocking the high-frequency `cached_status_bg` task. pub monitor: Arc>, pub metrics_history: std::sync::Mutex, pub cluster: Arc, pub sessions: Arc, pub vms: std::sync::Mutex, /// UPS staged-shutdown engine runtime (live status, latches, log). pub ups: Arc, pub cluster_secret: String, pub join_token: String, /// Pending one-time, short-TTL join tokens (cluster-join hardening). /// In-memory, 15-minute TTL, single-use. The static per-install /// `join_token` above still works alongside these for backward compat. pub one_time_join_tokens: Arc, /// Single-use bootstrap grants minted by THIS node's join-handshake on /// success. The joining master presents one back on /api/cluster/secret/ /// receive, letting a node that currently holds a DIFFERENT secret adopt /// the fleet secret right after an admin-authenticated join (closes the /// "added a node but its containers don't show" gap). Consumed on use. pub bootstrap_grants: Arc, pub pbs_restore_progress: std::sync::Mutex, pub ai_agent: Arc, /// Pre-built agent status response, updated by the self-monitor loop (every 2s on a manager, 5s on an agent) pub cached_status: Arc>>, /// WolfRun orchestration state pub wolfrun: Arc, pub wolffunctions: Arc, pub wolfflow: Arc, /// Status page monitoring state pub statuspage: Arc, /// Whether this server has TLS enabled (HTTPS on main port) pub tls_enabled: bool, /// Login rate limiter (brute-force protection) pub login_limiter: Arc, /// Brute-force protection — extends the ban engine to container ssh/web logs. pub bruteforce: Arc, pub scan_detector: Arc, pub diag_control: Arc, /// WireGuard bridge configs (cluster → bridge) pub wireguard_bridges: Arc>>, /// Patreon integration state pub patreon: Arc, /// Fleet Logs (loghub) — cluster log aggregation/retention state. pub loghub: Arc, /// Migration task progress tracker pub migration_tasks: Arc>>, /// Alert log — recent alerts surfaced to the frontend task log pub alert_log: Arc>>, /// Password reset tokens (in-memory, 30-minute expiry) pub password_reset_tokens: Arc, /// OIDC pending authentication flows (state token → flow data, 5-minute TTL) pub oidc_pending_flows: Arc>>, /// Image update watcher cache (container name → last check result) pub image_watcher_cache: Arc>>, /// Wakes the image-watcher loop early. /// /// That loop is phase-locked to this node's stagger slot with the interval /// floored at six hours, and it re-reads `enabled` only when it wakes. So /// enabling the watcher — by hand, by a settings push, or by the reconcile /// adopting a newer cluster rev — used to produce nothing at all for up to /// six hours, which reads exactly like a broken feature (RutgerDiehard /// 2026-08-19: "I've changed update settings to kick off an update cycle but /// it doesn't seem to help"). Notifying it makes the next sweep start now. pub image_watcher_wake: Arc, /// Integration framework state pub integrations: Arc, /// WolfRouter (native firewall/DHCP/DNS) state pub router: Arc, /// Predictive ops — pending/snoozed/dismissed proposals. pub predictive_proposals: Arc>, /// Predictive ops — operator-declared "this is intentional" suppressions. pub predictive_acks: Arc>, /// Predictive ops — rolling per-resource sample history. pub predictive_metrics: Arc>, /// 30-second aggregation cache for `/api/proposals/cluster`. Stores /// the most-recent fan-out result so dashboards refreshing every /// few seconds don't make N peers each round-trip per refresh. /// Invalidated on every state-changing predictive endpoint (snooze / /// dismiss / approve / run-now / ack create+delete) so operator /// actions produce immediately-visible feedback. pub predictive_cluster_cache: Arc>>, /// This node's identifier — copied here so predictive handlers /// can build proposal scopes without threading it from main. pub node_id: String, /// WolfStack Gateway store — universal SMB/NFS re-export layer. /// Cluster-synced via the existing inter-node secret pattern. pub gateways: Arc>, /// Federated remote clusters this WolfStack pulls from for /// cross-cluster aggregation (Shares panel today; future use: /// Control Panel inventory across separate sites). pub federations: Arc>, /// 30-second aggregation cache for `/api/gateways/cluster`. /// Same pattern as `predictive_cluster_cache` — a dashboard /// refresh every few seconds shouldn't translate into a fan-out /// to N peers + M federations on every refresh. Invalidated by /// every state-changing gateway / federation endpoint. pub gateway_cluster_cache: Arc>>, /// 30-second aggregation cache for `/api/array/cluster` — /// matches the gateway_cluster_cache pattern. Invalidated by /// every state-changing array endpoint (start, stop, parity, /// parity-cancel, schedule save) plus federation save/delete. pub array_cluster_cache: Arc>>, /// Registered Xen Orchestra (XCP-ng) instances. WolfStack drives /// XO via its REST API, the same way it drives Proxmox via PVE /// API. Each entry stores a base URL + an obfuscated API token. pub xo: Arc>, /// Host antivirus / rootkit scanning state — ClamAV + rkhunter + /// chkrootkit, with quarantine + process-kill on ClamAV hits. /// Per-host state; fleet aggregation via the fleet_fanout_get pattern. pub antivirus: Arc, } #[derive(Clone, Serialize, Deserialize)] pub struct AlertLogEntry { pub id: u64, pub timestamp: String, pub severity: String, pub title: String, pub detail: String, pub hostname: String, pub cluster: String, } #[derive(Clone, Serialize)] pub struct MigrationTask { pub id: String, pub stage: String, // "preflight", "stop_source", "export", "upload", "import", "start", "disk_copy", "done", "failed" pub message: String, pub completed: bool, pub error: Option, pub started_at: u64, /// 0.0–100.0 for the current stage, None when the stage has no /// progress signal (e.g. stopping a VM is treated as instantaneous). #[serde(skip_serializing_if = "Option::is_none")] pub percent: Option, /// Bytes observed on the target so far for this stage. #[serde(skip_serializing_if = "Option::is_none")] pub bytes_done: Option, /// Total bytes expected for this stage (archive size, disk size, …). #[serde(skip_serializing_if = "Option::is_none")] pub bytes_total: Option, } /// Load or generate the join token from /etc/wolfstack/join-token pub fn load_join_token() -> String { let path = std::path::Path::new("/etc/wolfstack/join-token"); if let Ok(token) = std::fs::read_to_string(path) { let token = token.trim().to_string(); if !token.is_empty() { return token; } } // Generate a new token use std::fmt::Write; let mut token = String::with_capacity(64); let random_bytes: [u8; 32] = { let mut buf = [0u8; 32]; // Use /dev/urandom for cryptographic randomness if let Ok(mut f) = std::fs::File::open("/dev/urandom") { use std::io::Read; let _ = f.read_exact(&mut buf); } else { // Fallback: use system time + pid let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); let seed = t.as_nanos() ^ (std::process::id() as u128); for (i, b) in buf.iter_mut().enumerate() { *b = ((seed >> (i % 16 * 8)) & 0xFF) as u8 ^ (i as u8).wrapping_mul(37); } } buf }; for b in &random_bytes { let _ = write!(token, "{:02x}", b); } // Save it with mode 0600. Pre-v18.7.27 the token was world-readable; // a local user could read it and forge a rogue cluster join request // against any other node. write_secure enforces 0600 even if the // file already exists with looser perms. if let Err(e) = crate::paths::write_secure(path.to_str().unwrap_or("/etc/wolfstack/join-token"), &token) { warn!("Could not save join token to {}: {}", path.display(), e); } token } // ─── Auth helpers ─── /// Extract session token from cookie pub(crate) fn get_session_token(req: &HttpRequest) -> Option { req.cookie("wolfstack_session") .map(|c| c.value().to_string()) } /// Response header stamped on every 401 that means "this operator's browser /// session is gone" — no cookie, or a cookie past the 8-hour session lifetime, /// or a session cleared by a restart or force-logout. /// /// The dashboard's global fetch interceptor keys on this header rather than on /// a bare 401, because plenty of endpoints answer 401 for reasons that must NOT /// throw the operator out to the login page: a mistyped admin password in the /// Add Node dialog, a peer presenting the wrong cluster secret, an invalid API /// key. Only the session paths below set it. pub const SESSION_EXPIRED_HEADER: &str = "X-WolfStack-Session"; /// Build the 401 for a dead operator session. Single definition so the header /// can't be forgotten on a path that adds one later. pub fn session_expired_response(error: &str) -> HttpResponse { HttpResponse::Unauthorized() .insert_header((SESSION_EXPIRED_HEADER, "expired")) .json(serde_json::json!({ "error": error })) } #[cfg(test)] mod session_expired_response_tests { use super::{session_expired_response, SESSION_EXPIRED_HEADER}; #[actix_web::test] async fn stamps_the_header_the_dashboard_bounces_on() { let resp = session_expired_response("Session expired"); assert_eq!(resp.status().as_u16(), 401); assert_eq!( resp.headers() .get(SESSION_EXPIRED_HEADER) .and_then(|v| v.to_str().ok()), Some("expired"), "web/js/app.js bounces to the login page on this header alone — a 401 \ without it is deliberately treated as an ordinary endpoint error so a \ wrong password in the Add Node dialog can't log the operator out", ); let body = actix_web::body::to_bytes(resp.into_body()).await.unwrap(); assert_eq!(body, r#"{"error":"Session expired"}"#); } } // ─── Read-only (viewer-role) sessions ──────────────────────────────── // // WolfStack users carry a role, "admin" or "viewer", and the docs promise // viewer = read-only. Until 2026-09-09 that promise was enforced on only // three endpoints (user management, cluster access, diagnostics); every // other mutation — package installs, container/VM lifecycle, backups, // settings, API-key minting — accepted any authenticated session. // Reported by VolkSec against POST /api/system/install-package (CWE-862). // // The fix lives at the ONE auth chokepoint rather than on 680 routes: a // session created for a non-admin role is flagged read-only at login // (`SessionManager::create_session`), and `require_auth` refuses it any // request that is not a safe method, except the small self-service set // below. Console / command sinks are GETs (WebSocket upgrades), so // `require_operator_auth` refuses read-only sessions regardless of method, // and `node_proxy` tells the far node when the actor it is forwarding is // read-only so the same refusal happens across the cluster. /// Response header stamped on every 403 that means "your account is /// read-only". The dashboard's fetch interceptor keys on it to show a /// visible explanation instead of a bare failed action. pub const READ_ONLY_HEADER: &str = "X-WolfStack-Role"; /// Request header `node_proxy` adds when the operator it is forwarding /// for holds a read-only session. `require_operator_auth` on the far node /// refuses the forwarded call when it is present. Set only by our own /// proxy from server-side session state — a browser cannot remove it. pub const PROXIED_ACTOR_ROLE_HEADER: &str = "X-WolfStack-Actor-Role"; /// Is the operator behind this request a WolfStack administrator? /// /// A direct session or API key: the local user store decides. A request a /// peer forwarded through `/api/nodes/{id}/proxy` arrives authenticated as /// "cluster-node" and carries no session here, so the forwarding node — /// which holds the operator's session — states the role in /// `X-WolfStack-Actor-Role: admin`. That header is trusted ONLY on a /// cluster-authenticated proxied request (the same trust the read-only flag /// and `X-WolfStack-Actor` already rely on); from any other caller it is /// ignored, so a browser cannot claim it. Found 2026-11-13: an admin could /// not reveal a mail cluster's admin sign-in when the cluster's record lived /// on another node. pub fn caller_is_admin(req: &HttpRequest, user: &str) -> bool { if user != "cluster-node" { return crate::auth::session_user_is_admin(user); } let proxied = req.headers().get("X-WolfStack-Proxied").and_then(|v| v.to_str().ok()) == Some("1"); proxied && req.headers().get(PROXIED_ACTOR_ROLE_HEADER).and_then(|v| v.to_str().ok()) == Some("admin") } /// The 403 every read-only refusal returns. pub fn read_only_forbidden(what: &str) -> HttpResponse { HttpResponse::Forbidden() .insert_header((READ_ONLY_HEADER, "read-only")) .json(serde_json::json!({ "error": format!("Your account is read-only (viewer role): {}. \ Ask an administrator to make the change or to \ change your role.", what), "read_only": true, })) } /// May a read-only session make THIS request? /// /// Safe methods (GET / HEAD / OPTIONS) always. Otherwise only the /// self-service account operations a viewer needs to keep their own /// login working — every one of them already scopes itself to the /// calling user (`require_admin_or_self`, passkey ownership checks, /// per-user preference storage), so the path match here is the gate on /// WHICH actions, not on WHOSE account. pub fn read_only_session_may(method: &actix_web::http::Method, path: &str, username: &str) -> bool { use actix_web::http::Method; if method.is_safe() { return true; } match (method, path) { // Ending the session, and per-user UI preferences. (&Method::POST, "/api/auth/logout") => true, (&Method::POST | &Method::PATCH, "/api/user/preferences") => true, // Own passkeys — the handlers bind the credential to the caller. (&Method::POST, "/api/auth/passkey/register/start") | (&Method::POST, "/api/auth/passkey/register/finish") => true, (&Method::DELETE, p) if p.starts_with("/api/auth/passkeys/") => true, // Own password / email / 2FA — the target segment must be the caller. (&Method::POST, p) => { let Some(rest) = p.strip_prefix("/api/auth/users/") else { return false }; let Some((target, action)) = rest.split_once('/') else { return false }; target == username && matches!(action, "password" | "email" | "2fa/setup" | "2fa/confirm" | "2fa/disable") } _ => false, } } /// Is the request carrying a live read-only session cookie? Used where a /// handler's request is a safe method (GET WebSocket upgrades, GET proxy /// calls) yet the operation behind it is not read-only. pub fn session_is_read_only(req: &HttpRequest, state: &web::Data) -> bool { get_session_token(req) .and_then(|t| state.sessions.validate_info(&t)) .map(|s| s.read_only) .unwrap_or(false) } #[cfg(test)] mod read_only_gate_tests { use super::{read_only_forbidden, read_only_session_may, READ_ONLY_HEADER}; use actix_web::http::Method; #[test] fn safe_methods_are_always_allowed() { assert!(read_only_session_may(&Method::GET, "/api/containers", "bob")); assert!(read_only_session_may(&Method::GET, "/api/system-check", "bob")); assert!(read_only_session_may(&Method::HEAD, "/api/status", "bob")); assert!(read_only_session_may(&Method::OPTIONS, "/api/status", "bob")); } #[test] fn the_reported_endpoint_and_other_mutations_are_refused() { // VolkSec, 2026-09-09: viewer could reach the package installer. assert!(!read_only_session_may(&Method::POST, "/api/system/install-package", "bob")); assert!(!read_only_session_may(&Method::POST, "/api/system/prepare-install-package", "bob")); // A viewer must not mint an API key either — keys have no owner // role, so a write-scoped key would be a standing bypass. assert!(!read_only_session_may(&Method::POST, "/api/tokens", "bob")); assert!(!read_only_session_may(&Method::POST, "/api/containers/docker/x/start", "bob")); assert!(!read_only_session_may(&Method::DELETE, "/api/backups/x", "bob")); assert!(!read_only_session_may(&Method::PUT, "/api/settings", "bob")); assert!(!read_only_session_may(&Method::PATCH, "/api/anything", "bob")); assert!(!read_only_session_may(&Method::POST, "/api/auth/users", "bob")); assert!(!read_only_session_may(&Method::PUT, "/api/auth/users/bob/clusters", "bob")); } #[test] fn self_service_account_operations_are_allowed_for_self_only() { assert!(read_only_session_may(&Method::POST, "/api/auth/logout", "bob")); assert!(read_only_session_may(&Method::POST, "/api/user/preferences", "bob")); assert!(read_only_session_may(&Method::PATCH, "/api/user/preferences", "bob")); assert!(read_only_session_may(&Method::POST, "/api/auth/passkey/register/start", "bob")); assert!(read_only_session_may(&Method::POST, "/api/auth/passkey/register/finish", "bob")); assert!(read_only_session_may(&Method::DELETE, "/api/auth/passkeys/abc", "bob")); for action in ["password", "email", "2fa/setup", "2fa/confirm", "2fa/disable"] { let own = format!("/api/auth/users/bob/{}", action); let other = format!("/api/auth/users/alice/{}", action); assert!(read_only_session_may(&Method::POST, &own, "bob"), "{}", own); assert!(!read_only_session_may(&Method::POST, &other, "bob"), "{}", other); } // Prefix look-alikes are not self-service. assert!(!read_only_session_may(&Method::POST, "/api/auth/users/bob/clusters", "bob")); assert!(!read_only_session_may(&Method::POST, "/api/auth/users/bob", "bob")); assert!(!read_only_session_may(&Method::POST, "/api/auth/logout-all", "bob")); } #[actix_web::test] async fn refusal_is_a_403_the_dashboard_can_recognise() { let resp = read_only_forbidden("installing packages"); assert_eq!(resp.status().as_u16(), 403); assert_eq!(resp.headers().get(READ_ONLY_HEADER).and_then(|v| v.to_str().ok()), Some("read-only")); let body = actix_web::body::to_bytes(resp.into_body()).await.unwrap(); let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(v["read_only"], true); assert!(v["error"].as_str().unwrap().contains("installing packages")); } } /// Cluster-secret-ONLY gate for peer-to-peer endpoints an operator never /// calls directly. Unlike `require_auth` there is no session or API-key /// fallback — these endpoints move key material between nodes, so the /// only acceptable caller is another node holding the cluster secret. /// /// Delegates to `auth::validate_inter_node_secret` rather than comparing /// against `state.cluster_secret` inline, for the reason documented on /// `require_auth`: the inline form misses the on-disk secret and has /// already caused drift between endpoints once. pub fn require_cluster_secret( req: &HttpRequest, state: &web::Data, ) -> Result<(), HttpResponse> { let provided = req.headers() .get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !provided.is_empty() && crate::auth::validate_inter_node_secret_from( provided, &state.cluster_secret, peer_ip(req)) { return Ok(()); } Err(HttpResponse::Unauthorized().json(serde_json::json!({ "error": "X-WolfStack-Secret missing or invalid" }))) } /// Transport-level source address of a request, for the cluster-secret /// peer gate. /// /// SECURITY: this deliberately uses `peer_addr()` — the real TCP peer — /// and NEVER `connection_info().realip_remote_addr()`, which honours /// `X-Forwarded-For`. That header is attacker-supplied; trusting it here /// would let anyone claim to be a recorded cluster peer and hand back the /// exact authentication bypass this gate exists to close. See /// `auth::default_secret_accepted_from`. pub fn peer_ip(req: &HttpRequest) -> Option { req.peer_addr().map(|a| a.ip()) } /// Second half of cluster-secret authentication: the per-node signature /// (`node_identity`). Runs only after the secret itself validated. /// /// Returns the verified sender's id when the request was signed by a /// pinned key; the operator gate uses it for the manager policy. /// /// * Transition mode (default): an unsigned or badly-signed request is /// logged and ACCEPTED — identical to pre-identity behaviour, so an /// older peer, a reinstalled node or an operator's own script keeps /// working. /// * Strict mode (operator opt-in): anything but a valid signature is /// refused, except on the join/bootstrap paths that exist to establish /// a key in the first place. pub fn peer_signature_gate(req: &HttpRequest) -> Result, HttpResponse> { use crate::node_identity::{mode, path_exempt_from_strict, verify_request, Mode, Verified}; match verify_request(req) { Verified::Node(id) => Ok(Some(id)), Verified::Unsigned => { if mode() == Mode::Strict && !path_exempt_from_strict(req.path()) { tracing::warn!("node identity: refused unsigned {} {} from {:?} (signatures required)", req.method(), req.path(), peer_ip(req)); return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "This cluster requires node signatures: a cluster secret alone is not \ accepted. Upgrade the calling node, or turn off 'Require node \ signatures' in Settings → Security (WOLFSTACK_NODE_SIGNATURES=off \ over SSH forces it off)." }))); } Ok(None) } Verified::Bad(why) => { if mode() == Mode::Strict { tracing::warn!("node identity: refused {} {} from {:?}: {}", req.method(), req.path(), peer_ip(req), why); return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": format!("Node signature rejected: {}", why) }))); } // Transition: say so in the log, then behave as before — never // break a cluster over a signature. tracing::warn!("node identity: {} {} from {:?} carried a signature that did not verify ({}); \ accepted on the cluster secret because signatures are not required", req.method(), req.path(), peer_ip(req), why); Ok(None) } } } /// Check if request is authenticated; returns username or error response pub fn require_auth(req: &HttpRequest, state: &web::Data) -> Result { // Accept internal requests from other WolfStack nodes if they provide the cluster secret. // Centralised three-way check (in-memory, on-disk, optional default) lives in // `auth::validate_inter_node_secret` — see Stage 5 docs there. Using the helper // (rather than open-coding the three checks here) keeps every endpoint's // behaviour identical and prevents drift like the pre-fix gap where // `require_cluster_auth` and 5 inline checks accepted the default // unconditionally even when Stage 5 was tightened. if let Some(val) = req.headers().get("X-WolfStack-Secret") { let provided = val.to_str().unwrap_or(""); if crate::auth::validate_inter_node_secret_from( provided, &state.cluster_secret, peer_ip(req)) { return peer_signature_gate(req).map(|_| "cluster-node".to_string()); } // Invalid secret — do NOT fall through to session auth return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Invalid cluster secret" }))); } // Accept API key authentication (X-API-Key header or Authorization: Bearer wsk_...) // Check platform calibration state for token-based auth if crate::compat::platform_ready() { let api_key_value = req.headers().get("X-API-Key") .and_then(|v| v.to_str().ok().map(|s| s.to_string())) .or_else(|| { req.headers().get("Authorization") .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .filter(|v| v.starts_with("wsk_")) .map(|v| v.to_string()) }); if let Some(raw_key) = api_key_value { // to_canonical: a dual-stack [::] listener reports v4 clients // as ::ffff:a.b.c.d — the key's IP allowlist stores plain v4. let ip = req.peer_addr().map(|a| a.ip().to_canonical().to_string()).unwrap_or_default(); match crate::compat::validate_key(&raw_key, Some(&ip)) { Some(key) => { let method = req.method().as_str(); let path = req.path(); if !crate::compat::scope_allows(&key, method, path) { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": crate::compat::rt_msg(3), }))); } crate::compat::audit_log(&crate::compat::AuditEntry { timestamp: chrono::Utc::now().to_rfc3339(), key_name: key.name.clone(), key_id: key.id.clone(), method: method.to_string(), path: path.to_string(), ip, status: 200, }); return Ok(format!("apikey:{}", key.name)); } None => { return Err(HttpResponse::Unauthorized().json(serde_json::json!({ "error": crate::compat::rt_msg(2) }))); } } } } match get_session_token(req) { Some(token) => { match state.sessions.validate_info(&token) { Some(session) => { // Viewer-role sessions are read-only. This is THE // enforcement point for every route that authenticates // through here — see the read-only section above. if session.read_only && !read_only_session_may(req.method(), req.path(), &session.username) { tracing::warn!("auth: read-only session '{}' refused {} {} from {:?}", session.username, req.method(), req.path(), peer_ip(req)); return Err(read_only_forbidden("this action changes the system")); } Ok(session.username) } None => Err(session_expired_response("Session expired")), } } None => Err(session_expired_response("Not authenticated")), } } /// Auth gate for endpoints that run caller-supplied commands or open an /// interactive shell. /// /// # Why this exists /// /// Third recommendation of the 2026-08-01 report by Dostxodjayev /// Abdullox (@squeeze440): *"a peer node legitimately proxying /// dashboard/API calls does not need blanket authority to run arbitrary /// shell commands inside every container; a narrower peer-scoped /// capability would shrink the blast radius of this credential class /// even after the default-secret issue above is fixed."* /// /// The cluster secret is a single symmetric credential shared by every /// node, so it cannot cryptographically stop a secret-holder from doing /// what a peer can do. What it CAN do is stop the credential class from /// being a one-header path to a root shell: /// /// **Accepts** /// * a real operator — session cookie or API key (the normal path) /// * a peer forwarding an operator's action: a cluster secret that is /// NOT the built-in default, together with `X-WolfStack-Proxied: 1` /// and `X-WolfStack-Actor` naming the operator upstream. Only /// `node_proxy` / `remote_console_bridge` stamp those, and only /// when their own caller was a real operator rather than another /// peer — so the attribution cannot be chained by a secret-holder. /// /// **Rejects** /// * the built-in default secret, unconditionally — even from a /// recorded peer, and even when `WOLFSTACK_ACCEPT_DEFAULT_SECRET=1`. /// The published constant never reaches a shell, full stop. This is /// defence in depth layered on top of the peer gate in /// `auth::default_secret_accepted_from`. /// * a bare cluster secret with no operator attribution — node-to-node /// state sync has no business opening a shell. pub fn require_operator_auth( req: &HttpRequest, state: &web::Data, ) -> Result { if let Some(val) = req.headers().get("X-WolfStack-Secret") { let provided = val.to_str().unwrap_or(""); // The published constant NEVER authorises command execution. if crate::auth::validate_cluster_secret(provided, crate::auth::default_cluster_secret()) { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "The built-in default cluster secret cannot authorise command \ execution. Rotate to a per-install secret: Settings → Security \ → Rotate cluster secret." }))); } if !crate::auth::validate_inter_node_secret_from( provided, &state.cluster_secret, peer_ip(req)) { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Invalid cluster secret" }))); } // Which node is forwarding? With a verified signature the manager // policy applies: only nodes the operator left as managers may // forward operator actions. In Strict mode a forwarded action // without a verified sender is refused outright — that is the // header-forgery hole of GHSA-r3mw-2wmq-j6jg revision 2 closed. let signer = peer_signature_gate(req)?; match signer.as_deref() { Some(node_id) => { let is_manager = state.cluster.get_all_nodes().into_iter() .find(|n| n.id == node_id || n.self_id.as_deref() == Some(node_id)) .map(|n| n.manager) .unwrap_or(false); if !is_manager { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": format!("Node {} is not permitted to forward operator actions \ (its 'manager' setting is off).", node_id) }))); } } None if crate::node_identity::mode() == crate::node_identity::Mode::Strict => { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "This endpoint requires a forwarded operator action signed by a \ manager node; node signatures are required on this cluster." }))); } None => {} } let proxied = req.headers().get("X-WolfStack-Proxied") .and_then(|v| v.to_str().ok()) == Some("1"); // The forwarding node tells us when the operator behind this call // holds a read-only session; consoles and command execution are // never available to a viewer, on any node. if req.headers().get(PROXIED_ACTOR_ROLE_HEADER) .and_then(|v| v.to_str().ok()) == Some("read-only") { return Err(read_only_forbidden("consoles and command execution are not available")); } let actor = req.headers().get("X-WolfStack-Actor") .and_then(|v| v.to_str().ok()) .map(|s| s.trim()) .filter(|s| !s.is_empty() && *s != "cluster-node"); return match (proxied, actor) { (true, Some(a)) => Ok(format!("{} (via peer)", a)), _ => Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "This endpoint executes commands and requires an operator \ identity. A cluster-secret-only request is not sufficient; \ use a session or API key, or reach it through \ /api/nodes/{id}/proxy as a logged-in operator." }))), }; } // No cluster-secret header — fall through to session / API-key auth. let who = require_auth(req, state)?; // Console and exec sinks are reached with GET (WebSocket upgrade) or // hand out a ticket on GET, so require_auth's method rule alone would // let a read-only session through. Refuse them here regardless of method. if session_is_read_only(req, state) { tracing::warn!("auth: read-only session '{}' refused operator sink {} {} from {:?}", who, req.method(), req.path(), peer_ip(req)); return Err(read_only_forbidden("consoles and command execution are not available")); } Ok(who) } /// Require cluster secret authentication for inter-node endpoints pub fn require_cluster_auth(req: &HttpRequest, state: &web::Data) -> Result<(), HttpResponse> { match req.headers().get("X-WolfStack-Secret") { Some(val) => { let provided = val.to_str().unwrap_or(""); // Centralised three-way check (in-memory, on-disk, optional default) // — see auth::validate_inter_node_secret. The pre-Stage-5 version // of this helper accepted the hardcoded default unconditionally, // bypassing the Stage 5 env-flag gate that was applied to require_auth. // 13+ endpoints use this helper and inherited that gap; fixed here. if crate::auth::validate_inter_node_secret_from( provided, &state.cluster_secret, peer_ip(req)) { peer_signature_gate(req).map(|_| ()) } else { Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Invalid cluster secret" }))) } } None => Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Cluster authentication required" }))), } } // ─── Auth API ─── #[derive(Deserialize)] pub struct LoginRequest { pub username: String, pub password: String, #[serde(default)] pub totp_code: String, } /// POST /api/auth/login — authenticate with Linux or WolfStack credentials + optional 2FA pub async fn login(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Rate limiting — extract client IP. Strip the :port suffix that // actix attaches to peer_addr() so the limiter keys on bare IP // (otherwise every connection from the same client gets its own // bucket because the source port changes). let raw_ip = req.connection_info().peer_addr().unwrap_or("unknown").to_string(); // canonical_ip_str: a dual-stack [::] listener reports v4 clients as // ::ffff:a.b.c.d — without this the lockout bucket keys the mapped // form and kernel_block_ip would write a (no-op) ip6tables rule for // what is really IPv4-wire traffic. let client_ip = crate::netaddr::canonical_ip_str(&strip_port(&raw_ip)).into_owned(); if state.login_limiter.is_locked_out(&client_ip) { state.login_limiter.audit_blocked(&client_ip, &body.username); return HttpResponse::Forbidden().json(serde_json::json!({ "success": false, "error": "Access denied — this IP is blocked. Contact the operator.", })); } // Check if direct login is disabled on this node { let nodes = state.cluster.nodes_read(); if let Some(self_node) = nodes.get(&state.cluster.self_id) && self_node.login_disabled { return HttpResponse::Forbidden().json(serde_json::json!({ "success": false, "error": "Direct login is disabled on this server. Access it via the primary dashboard." })); } } let auth_config = crate::auth::users::AuthConfig::load(); let mode = auth_config.auth_mode.as_str(); // Try WolfStack users first (if mode is "wolfstack" or "both") if (mode == "wolfstack" || mode == "both") && let Some(user) = crate::auth::users::authenticate_wolfstack_user(&body.username, &body.password) { // Check 2FA if enabled if user.totp_enabled { if body.totp_code.is_empty() { // Password correct, but 2FA required — tell frontend to prompt return HttpResponse::Ok().json(serde_json::json!({ "success": false, "requires_2fa": true, "message": "Two-factor authentication required" })); } if !crate::auth::users::verify_totp(&user.totp_secret, &body.totp_code) { state.login_limiter.record_failure(&client_ip); return HttpResponse::Unauthorized().json(serde_json::json!({ "success": false, "error": "Invalid two-factor authentication code" })); } } state.login_limiter.clear_with(&client_ip, &body.username); crate::auth::record_admin_ip(&client_ip); // The user's role decides whether this session may change // anything — see the read-only section near require_auth. let read_only = crate::auth::role_is_read_only(&user.role); let token = state.sessions.create_session(&body.username, read_only); let mut cookie = Cookie::build("wolfstack_session", &token) .path("/") .http_only(true) // Lax, not Strict: Strict withholds the session cookie on // top-level navigations/redirects, which broke login on // Microsoft Edge (stricter tracking-prevention than Chrome) — // users authenticated then immediately appeared logged out. // Lax still blocks cross-site POSTs (CSRF) for this same-origin SPA. .same_site(actix_web::cookie::SameSite::Lax) .max_age(actix_web::cookie::time::Duration::hours(8)) .finish(); if state.tls_enabled { cookie.set_secure(true); } return HttpResponse::Ok() .cookie(cookie) .json(serde_json::json!({ "success": true, "username": body.username, "read_only": read_only, })); } // Try Linux system auth (if mode is "linux" or "both") if (mode == "linux" || mode == "both") && crate::auth::authenticate_user(&body.username, &body.password) { state.login_limiter.clear_with(&client_ip, &body.username); crate::auth::record_admin_ip(&client_ip); // A Linux account has no WolfStack role: full access, as before. let token = state.sessions.create_session(&body.username, false); let mut cookie = Cookie::build("wolfstack_session", &token) .path("/") .http_only(true) // Lax, not Strict: Strict withholds the session cookie on // top-level navigations/redirects, which broke login on // Microsoft Edge (stricter tracking-prevention than Chrome) — // users authenticated then immediately appeared logged out. // Lax still blocks cross-site POSTs (CSRF) for this same-origin SPA. .same_site(actix_web::cookie::SameSite::Lax) .max_age(actix_web::cookie::time::Duration::hours(8)) .finish(); if state.tls_enabled { cookie.set_secure(true); } return HttpResponse::Ok() .cookie(cookie) .json(serde_json::json!({ "success": true, "username": body.username })); } // record_failure_with fires the limiter's propagation hook // automatically when the threshold is hit — installed by main.rs // at startup. No manual fanout needed here; the same hook also // fires for sshd / pvedaemon failures detected by log_monitor. state.login_limiter.record_failure_with(&client_ip, &body.username); HttpResponse::Unauthorized().json(serde_json::json!({ "success": false, "error": "Invalid username or password" })) } /// Fan out a kernel-block decision to every federation registered on /// this WolfStack. Uses each federation's stored api_key as a Bearer /// token to authenticate against the federation's /// `/api/security/fleet-kernel-block-ip` endpoint — which applies the /// block locally AND fans out within the federation's own cluster. /// /// Crucially the receiving endpoint does NOT push back to federations, /// preventing the obvious A→B→A loop. Only the original local block /// trigger ever calls this function. pub async fn propagate_kernel_block_to_federations( federations: std::sync::Arc>, ip: String, lockout_seconds: u64, source_node: String, ) { let entries: Vec = { let g = match federations.read() { Ok(g) => g, Err(_) => return }; g.clusters.clone() }; if entries.is_empty() { return; } let payload = serde_json::json!({ "ip": ip, "lockout_seconds": lockout_seconds, "source_node": source_node, }); for fed in entries { let client = match reqwest::Client::builder() .danger_accept_invalid_certs(fed.insecure_tls) .timeout(std::time::Duration::from_secs(8)) .build() { Ok(c) => c, Err(e) => { tracing::error!("federation kernel-block: client build for '{}': {}", fed.name, e); continue; } }; let url = format!("{}/api/security/fleet-kernel-block-ip", fed.base_url.trim_end_matches('/')); match client.post(&url) .header("Authorization", format!("Bearer {}", fed.api_key)) .json(&payload) .send().await { Ok(resp) if resp.status().is_success() => { tracing::info!( "federation kernel-block: '{}' ({}) ack'd block of {}", fed.name, fed.base_url, ip); } Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); tracing::error!( "federation kernel-block to '{}' ({}) FAILED: HTTP {}: {}", fed.name, fed.base_url, status, body.chars().take(200).collect::()); } Err(e) => { tracing::error!( "federation kernel-block to '{}' ({}) FAILED: transport: {}", fed.name, fed.base_url, e); } } } } /// Fan out a kernel-block decision to every WolfStack peer in the /// cluster. Each peer receives `{ip, lockout_seconds, source_node}` and /// re-validates against its own trusted-IP list before applying. Called /// from the limiter's installed hook (main.rs wires it). pub async fn propagate_kernel_block_to_peers( cluster: std::sync::Arc, secret: String, ip: String, lockout_seconds: u64, source_node: String, ) { let nodes: Vec = { let n = cluster.nodes_read(); n.values() .filter(|p| p.id != cluster.self_id && p.node_type == "wolfstack") .cloned() .collect() }; if nodes.is_empty() { return; } let payload = serde_json::json!({ "ip": ip, "lockout_seconds": lockout_seconds, "source_node": source_node, }); // Shared pooled client (same inter-node TLS policy). This hook fires on // every login-limiter lockout — under a brute-force storm that is // continuous, and a fresh per-call Client::builder() opened (and leaked) a // new connection pool to every peer per lockout event. The pooled client // reuses keep-alive sockets and adds a 3s connect_timeout so a // FD-exhausted peer can't pin the fanout for the full request budget. let client = &*API_HTTP_CLIENT; for node in nodes { // v23.12: build_node_urls is the canonical HTTPS-first chain // (HTTPS → HTTP-over-WolfNet if known → legacy plaintext for // pre-v23.11 peers). The old hardcoded {HTTPS, HTTP-port+1} // pair stopped working against CA-signed-cert peers in v23.12 // because they no longer bind 8554. let urls = build_node_urls(&node.address, node.port, "/api/security/kernel-block-ip"); let mut last_err = String::from("no attempts"); let mut acked = false; for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&secret) .json(&payload) .send().await; match r { Ok(resp) if resp.status().is_success() => { tracing::info!("kernel-block fanout: {} ack'd block of {}", node.hostname, ip); // Drain so the keep-alive socket returns to the pool. drain_response(resp).await; acked = true; break; } Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); let body_preview = body.chars().take(200).collect::(); last_err = format!("{} -> HTTP {}: {}", url, status, body_preview); } Err(e) => { last_err = format!("{} -> transport: {}", url, e); } } } if !acked { // Log loudly — silent failure on a fleet-security // operation is exactly what hid the v23.10.0/.1 auth bug. tracing::error!( "kernel-block fanout to {} ({}) FAILED — block was applied locally but did NOT propagate. Last error: {}", node.hostname, node.address, last_err ); } } } #[derive(Deserialize)] pub struct KernelBlockRequest { pub ip: String, #[serde(default = "default_propagated_lockout")] pub lockout_seconds: u64, #[serde(default)] pub source_node: String, } fn default_propagated_lockout() -> u64 { 48 * 3600 } /// POST /api/security/kernel-block-ip — receive a fleet-propagated /// block. Authenticates via X-WolfStack-Secret (peer call) OR session /// (operator manually triggering). Each receiver re-validates against /// its own trusted-IP list before applying — an attacker can't cause /// your admin IP to be blocked elsewhere just because one node treats /// it as untrusted. pub async fn security_kernel_block_ip( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // require_auth accepts ANY of three valid cluster secrets // (loaded / hardcoded / on-disk) OR an authenticated session. // Rolling our own check here meant peers running with a custom // cluster secret (the standard production setup) were rejected. let actor = match require_auth(&req, &state) { Ok(a) => a, Err(e) => return e }; let body = body.into_inner(); let source = if body.source_node.is_empty() { "operator".to_string() } else { body.source_node.clone() }; // An OPERATOR-initiated block overrides the sticky 30-day peer // protection: lift it first so the block lands on a removed/untrusted // ex-peer. LIVE cluster members re-enter the protected set on the next // sync tick, so nodes still can't block each other. The decision keys // off the AUTHENTICATED identity, never the client-supplied // source_node field: require_auth returns the session username for a // dashboard operator, "cluster-node" for a secret-holding peer, and // "apikey:…" for automation — a rogue peer or leaked key must not be // able to strip a manager's ban protection and then block it. if actor != "cluster-node" && !actor.starts_with("apikey:") { let pip = body.ip.clone(); let _ = web::block(move || crate::auth::forget_known_peer_ip(&pip)).await; } state.login_limiter.add_propagated_lockout(&body.ip, body.lockout_seconds, &source); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "ip": body.ip, "applied": true, })) } /// POST /api/security/fleet-kernel-block-ip — federation entry point. /// Accepts a block triggered by another (federated) cluster, applies /// it locally, and fans it out across THIS cluster's WolfStack peers /// via `propagate_kernel_block_to_peers`. Crucially does NOT push /// back to federations — that's how we break the A→B→A→B propagation /// loop. The original-trigger cluster is the only one that calls /// every federation; receivers only fan within their own ring. /// /// Auth: require_auth — accepts cluster_secret OR Bearer api_key /// (federations use the latter) OR an authenticated session. pub async fn security_fleet_kernel_block_ip( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let source = if body.source_node.is_empty() { "federation".to_string() } else { format!("federation:{}", body.source_node) }; // 1. Apply locally — kernel-block + lockout list update. state.login_limiter.add_propagated_lockout(&body.ip, body.lockout_seconds, &source); // 2. Fan out within THIS cluster — every peer of ours sees it. // Skipping any further federation push to avoid loops. let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); let ip = body.ip.clone(); let secs = body.lockout_seconds; let source_node = state.cluster.self_id.clone(); tokio::spawn(async move { propagate_kernel_block_to_peers(cluster, secret, ip, secs, source_node).await; }); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "ip": body.ip, "applied": true, "fanning_out_to_cluster": true, })) } // ════════════════════════════════════════════════════════════════════ // Abuse reporting — compose + send via SMTP // See src/abuse_report/mod.rs. // ════════════════════════════════════════════════════════════════════ #[derive(Deserialize)] pub struct AbuseReportPreviewQuery { pub ip: String } /// GET /api/security/abuse-report/preview?ip=X — return whois data, /// evidence audit lines, and a pre-composed draft email so the UI /// can render the editable report modal. Cool-down state is also /// returned so the UI can warn if we recently reported this IP. pub async fn abuse_report_preview( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let ip = query.ip.clone(); if ip.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "missing required query parameter: ip", })); } // whois shells out — wrap in web::block so the actix runtime // doesn't stall on slow whois servers. let ip_for_whois = ip.clone(); let whois = web::block(move || crate::abuse_report::whois_lookup(&ip_for_whois)) .await .unwrap_or_default(); let evidence = crate::abuse_report::collect_evidence(&state.login_limiter, &ip, 100); let our_hostname = hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_else(|_| "this node".into()); // Draft preview sender: prefer the explicit From address, fall back to the // login user (matches resolve_from_mailbox's precedence) so a relay-only // setup with no SMTP user still shows the right sender in the draft. let from_email = state.ai_agent.config.lock() .map(|c| if c.smtp_from.trim().is_empty() { c.smtp_user.clone() } else { c.smtp_from.clone() }) .unwrap_or_default(); let draft = crate::abuse_report::compose_report( &ip, &whois, &evidence, &our_hostname, &from_email); let history = crate::abuse_report::ReportHistory::load(); let last = history.last_for(&ip).cloned(); let cooldown_remaining = history.cooldown_remaining_secs( &ip, crate::abuse_report::default_cooldown_days()); HttpResponse::Ok().json(serde_json::json!({ "ip": ip, "whois": whois, "evidence": evidence, "draft": draft, "last_report": last, "cooldown_remaining_secs": cooldown_remaining, "cooldown_days": crate::abuse_report::default_cooldown_days(), })) } #[derive(Deserialize)] pub struct AbuseReportSendBody { pub ip: String, pub to: String, pub subject: String, pub body: String, /// When true, send even if the cool-down window hasn't elapsed /// since the previous report for this IP. Operator-driven escape /// hatch for repeat offenders the abuse desk hasn't actioned. #[serde(default)] pub override_cooldown: bool, /// Number of evidence lines included in the body — recorded in /// history for audit purposes (the body itself isn't kept). #[serde(default)] pub evidence_count: usize, } /// POST /api/security/abuse-report/send — send the abuse-report email. /// 409 if cool-down is active and `override_cooldown` is false. pub async fn abuse_report_send( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); if body.ip.trim().is_empty() || body.to.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "ip and to are required", })); } if !body.override_cooldown { let history = crate::abuse_report::ReportHistory::load(); let remaining = history.cooldown_remaining_secs( &body.ip, crate::abuse_report::default_cooldown_days()); if remaining > 0 { return HttpResponse::Conflict().json(serde_json::json!({ "error": "cool-down active for this IP — set override_cooldown=true to send anyway", "cooldown_remaining_secs": remaining, })); } } let ai_config = match state.ai_agent.config.lock() { Ok(g) => g.clone(), Err(_) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "AI config lock poisoned", })), }; let draft = crate::abuse_report::ReportDraft { to: body.to.clone(), subject: body.subject.clone(), body: body.body.clone(), }; let ip = body.ip.clone(); let evidence_count = body.evidence_count; let result = web::block(move || { crate::abuse_report::send_report(&ai_config, &ip, &draft, evidence_count) }).await; match result { Ok(Ok(rec)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "record": rec, })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("send task panicked: {}", e), })), } } /// GET /api/security/abuse-report/history — last N abuse reports we sent. pub async fn abuse_report_history( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let hist = crate::abuse_report::ReportHistory::load(); HttpResponse::Ok().json(serde_json::json!({ "reports": hist.reports, "cooldown_days": crate::abuse_report::default_cooldown_days(), })) } /// GET /api/security/auth-config — current lockout settings. pub async fn security_auth_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(state.login_limiter.config()) } /// POST /api/security/auth-config — update lockout settings. pub async fn security_auth_config_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match state.login_limiter.set_config(body.into_inner()) { Ok(saved) => HttpResponse::Ok().json(saved), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ---- Brute-force protection (per-node) -------------------------------------- // These are the node-local endpoints. The fleet_* wrappers below fan them out // across the cluster; a peer that receives a propagated call lands here too. /// GET /api/bruteforce/status — this node's watched sources + active bans + /// per-source hit counts. pub async fn bruteforce_status_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(state.bruteforce.status_json()) } /// POST /api/bruteforce/config — set this node's config and (re)apply the /// monitors. The fleet wrapper propagates the identical body to peers, so no /// self-propagation is done here. pub async fn bruteforce_config_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match state.bruteforce.set_config_and_apply(body.into_inner()) { Ok(saved) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "config": saved, "watched_sources": state.bruteforce.sources.read().unwrap().clone(), })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/bruteforce/scan — re-run discovery and reattach on this node, /// returning the sources now watched (drives the live scan feedback). pub async fn bruteforce_scan( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let sources = state.bruteforce.rescan(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "watched_sources": sources, "active_bans": state.bruteforce.status_json().get("active_bans").cloned().unwrap_or(serde_json::Value::Array(vec![])), })) } // ---- Brute-force protection (fleet) ----------------------------------------- /// GET /api/fleet/bruteforce/status — aggregated status across every WolfStack /// node in the cluster. pub async fn fleet_bruteforce_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let self_id = state.cluster.self_id.clone(); let state_for_local = state.clone(); let local = move || state_for_local.bruteforce.status_json(); let results = fleet_fanout_get::( &state, "/api/bruteforce/status", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results, "self_id": self_id })) } /// POST /api/fleet/bruteforce/config — push one config to every node and apply. pub async fn fleet_bruteforce_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = body.into_inner(); let payload = serde_json::to_value(&cfg).unwrap_or(serde_json::json!({})); let state_for_local = state.clone(); let cfg_for_local = cfg.clone(); let local = move || match state_for_local.bruteforce.set_config_and_apply(cfg_for_local) { Ok(saved) => serde_json::json!({ "ok": true, "config": saved }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }; let results = fleet_fanout_post::( &state, "/api/bruteforce/config", payload, &[], Some(Ok(local())), FANOUT_SLOW, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// POST /api/fleet/bruteforce/scan — rescan + reattach on every node, returning /// each node's discovered sources for live feedback. pub async fn fleet_bruteforce_scan( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let self_id = state.cluster.self_id.clone(); let state_for_local = state.clone(); let local = move || { let sources = state_for_local.bruteforce.rescan(); serde_json::json!({ "ok": true, "watched_sources": sources }) }; let results = fleet_fanout_post::( &state, "/api/bruteforce/scan", serde_json::json!({}), &[], Some(Ok(local())), FANOUT_SLOW, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results, "self_id": self_id })) } #[derive(Deserialize)] pub struct GandalfSetRequest { pub enabled: bool, } /// GET /api/security/gandalf — current toggle state. pub async fn gandalf_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(serde_json::json!({ "enabled": state.diag_control.is_enabled(), "port": crate::diag::PORT, })) } /// POST /api/security/gandalf — flip the toggle. pub async fn gandalf_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } state.diag_control.set_enabled(body.enabled); HttpResponse::Ok().json(serde_json::json!({ "enabled": state.diag_control.is_enabled(), "port": crate::diag::PORT, })) } /// GET /api/security/auth-lockouts — currently-locked IPs and audit log. pub async fn security_auth_lockouts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let lockouts: Vec<_> = state.login_limiter.current_lockouts() .into_iter() .map(|(ip, secs, user)| serde_json::json!({ "ip": ip, "remaining_seconds": secs, "last_username": user, })) .collect(); HttpResponse::Ok().json(serde_json::json!({ "lockouts": lockouts, "audit": state.login_limiter.audit_log(), "config": state.login_limiter.config(), })) } #[derive(Deserialize)] pub struct UnblockRequest { pub ip: String, /// If true, also tell every peer to unblock. Defaults to true so /// the operator's "unblock my home IP" works fleet-wide. #[serde(default = "default_true_propagate")] pub propagate: bool, } fn default_true_propagate() -> bool { true } /// POST /api/security/auth-unblock — operator-triggered IP unblock. pub async fn security_auth_unblock( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let ip = body.ip.clone(); if web::block(move || { if body.propagate { // The limiter hook owns fleet propagation; do not also spawn it here. state.login_limiter.unblock(&body.ip); } else { state.login_limiter.unblock_local(&body.ip); } }).await.is_err() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Could not complete the IP unblock. Please retry." })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "ip": ip })) } pub async fn propagate_kernel_unblock_to_peers( cluster: std::sync::Arc, secret: String, ip: String, ) { let nodes: Vec = { let n = cluster.nodes_read(); n.values() .filter(|p| p.id != cluster.self_id && p.node_type == "wolfstack") .cloned() .collect() }; // Shared pooled client (same inter-node TLS policy) — see the block-fanout // twin above. A fresh per-call client leaked a pool per unblock event. let client = &*API_HTTP_CLIENT; let payload = serde_json::json!({ "ip": ip, "propagate": false }); for node in nodes { let urls = build_node_urls(&node.address, node.port, "/api/security/auth-unblock-peer"); let mut last_err = String::from("no attempts"); let mut acked = false; for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&secret) .json(&payload) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; acked = true; break; } Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); last_err = format!("{} -> HTTP {}: {}", url, status, body.chars().take(200).collect::()); } Err(e) => { last_err = format!("{} -> transport: {}", url, e); } } } if !acked { tracing::error!( "kernel-unblock fanout to {} ({}) FAILED. Last error: {}", node.hostname, node.address, last_err ); } else { tracing::info!("kernel-unblock fanout: {} ack'd unblock of {}", node.hostname, ip); } } } /// POST /api/security/auth-unblock-peer — receive a fleet-propagated /// unblock. Cluster-secret only. pub async fn security_auth_unblock_peer( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Never forward a peer delivery, regardless of its propagate field. if web::block(move || state.login_limiter.unblock_local(&body.ip)).await.is_err() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Could not complete the IP unblock. Please retry." })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } /// Strip the trailing `:port` from a `peer_addr()` string. Actix /// returns `1.2.3.4:56789` (or `[::1]:56789` for v6) — we want the /// bare IP for the rate limiter so all connections from one client /// share a bucket. Delegates to netaddr::strip_port, which also keeps /// a bare (portless) IPv6 literal intact instead of eating its last /// group as a "port". fn strip_port(addr: &str) -> String { crate::netaddr::strip_port(addr).to_string() } /// GET /api/settings/login-disabled — check if direct login is disabled (no auth needed) pub async fn login_disabled_status(state: web::Data) -> HttpResponse { let disabled = { let nodes = state.cluster.nodes_read(); nodes.get(&state.cluster.self_id).map(|n| n.login_disabled).unwrap_or(false) }; HttpResponse::Ok().json(serde_json::json!({ "login_disabled": disabled })) } /// POST /api/settings/site — set the operator-declared site tag on /// this node. Called by the master node when an admin edits a remote /// node's Site field (push path for immediate effect; gossip still /// propagates the value if the push happens to miss). Empty string /// clears the tag. pub async fn set_site(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let site_raw = body.get("site").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); // Cap at 64 chars so a malformed payload can't bloat the on-disk // file or the gossip payload. Operators use short labels in // practice ("home", "office-vlan10"); anything longer is a typo // or an abuse attempt. if site_raw.len() > 64 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "site tag too long (max 64 chars)" })); } let new_site = if site_raw.is_empty() { None } else { Some(site_raw.clone()) }; { let mut nodes = state.cluster.nodes_write(); if let Some(node) = nodes.get_mut(&state.cluster.self_id) { node.site = new_site.clone(); } } crate::agent::ClusterState::save_self_site(&site_raw); HttpResponse::Ok().json(serde_json::json!({ "site": new_site })) } /// POST /api/settings/roles — set the tier roles on THIS node. Called by the /// control node when an admin edits a node's roles (push path for immediate /// effect; gossip re-asserts the value on the next poll anyway). Body: /// `{"roles": ["dns", "mail_relay"]}`. An empty list clears all roles /// (general-purpose node). pub async fn set_roles(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Parse into the typed enum, dropping any token this build doesn't know // (serde maps unknown → NodeRole::Unknown; we filter those out so an // operator can never persist a role the node can't act on). let roles: Vec = body.get("roles") .and_then(|v| serde_json::from_value::>(v.clone()).ok()) .unwrap_or_default() .into_iter() .filter(|r| *r != crate::agent::NodeRole::Unknown) .collect::>() // dedup, stable order .into_iter() .collect(); { let mut nodes = state.cluster.nodes_write(); if let Some(node) = nodes.get_mut(&state.cluster.self_id) { node.roles = roles.clone(); } } crate::agent::ClusterState::save_self_roles(&roles); HttpResponse::Ok().json(serde_json::json!({ "roles": roles })) } /// POST /api/settings/poll-interval — set THIS node's low-traffic poll /// interval. Called by the node where an admin edited it (see /// `update_node_settings`). Body: `{"poll_interval_secs": 60}`; 10 restores /// the default cadence. Takes effect on the next poll tick and is advertised /// to every peer in this node's next status report. pub async fn set_poll_interval(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let Some(secs) = body.get("poll_interval_secs").and_then(|v| v.as_u64()) .filter(|s| crate::agent::POLL_INTERVAL_CHOICES.contains(s)) else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("poll_interval_secs must be one of {:?}", crate::agent::POLL_INTERVAL_CHOICES) })); }; match state.cluster.set_self_poll_interval(Some(secs)) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "poll_interval_secs": secs })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/cluster/roles/available — the assignable tier roles (value + /// label) for the node-settings role picker. pub async fn cluster_roles_available(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let roles: Vec = crate::agent::NodeRole::assignable().iter().map(|r| { // serde snake_case value is what the API round-trips; label is UI text. let value = serde_json::to_value(r).ok() .and_then(|v| v.as_str().map(String::from)) .unwrap_or_default(); serde_json::json!({ "value": value, "label": r.label() }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "roles": roles })) } /// GET /api/cluster/roles/summary — per-role membership across the cluster, /// so the UI can show "DNS tier: 3 nodes" and warn when a tier is thin. pub async fn cluster_roles_summary(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let summary: Vec = crate::agent::NodeRole::assignable().iter().map(|r| { let nodes: Vec = state.cluster.nodes_with_role(*r).iter().map(|n| { serde_json::json!({ "id": n.id, "hostname": n.display_name.clone().unwrap_or_else(|| n.hostname.clone()), "online": n.online, }) }).collect(); let value = serde_json::to_value(r).ok() .and_then(|v| v.as_str().map(String::from)) .unwrap_or_default(); serde_json::json!({ "role": value, "label": r.label(), "count": nodes.len(), "nodes": nodes }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "tiers": summary })) } // ─── WolfHost DNS tier — apply a zone op on THIS node's PowerDNS ─── // // These run the WolfHost DNS provisioning locally on whichever node // receives them. The WolfHost control node fans a zone change out to // every node carrying the `dns` role by POSTing here (locally for a // self/ingress node, via the node proxy for remotes) — that's how a // single "create zone" lands on all ≥3 nameservers. Cluster-auth only: // this is an internal tier RPC, never operator-facing. /// Ensure PowerDNS is installed on this node, then apply. Idempotent — /// `install_powerdns` is a no-op reinstall when it's already present. fn dns_tier_ensure_pdns() -> Result<(), String> { if crate::wolfhost::provisioning::dns::is_pdns_running() { return Ok(()); } crate::wolfhost::provisioning::dns::install_powerdns() } #[derive(serde::Deserialize)] pub struct DnsApplyZone { pub domain: String, pub host_ip: String, pub ns1: String, pub ns2: String, } /// POST /api/wolfhost-dns/apply-zone — create/replace a zone here. pub async fn dns_tier_apply_zone(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let b = body.into_inner(); let result = tokio::task::spawn_blocking(move || { dns_tier_ensure_pdns()?; crate::wolfhost::provisioning::dns::create_zone(&b.domain, &b.host_ip, &b.ns1, &b.ns2) }).await.unwrap_or_else(|e| Err(e.to_string())); match result { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(serde::Deserialize)] pub struct DnsApplyDeleteZone { pub domain: String } /// POST /api/wolfhost-dns/delete-zone — remove a zone here. pub async fn dns_tier_delete_zone(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let domain = body.into_inner().domain; let result = tokio::task::spawn_blocking(move || { crate::wolfhost::provisioning::dns::delete_zone(&domain) }).await.unwrap_or_else(|e| Err(e.to_string())); match result { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(serde::Deserialize)] pub struct DnsApplyRecord { pub domain: String, pub name: String, #[serde(rename = "type")] pub rtype: String, #[serde(default)] pub content: String, #[serde(default = "dns_default_ttl")] pub ttl: u32, /// true = delete this record, false/absent = set it. #[serde(default)] pub delete: bool, } fn dns_default_ttl() -> u32 { 3600 } /// POST /api/wolfhost-dns/record — set or delete one record here. No /// `ensure_pdns` here (nor in delete-zone): a record/zone op only ever /// follows a zone creation, which already installed PowerDNS on this node. pub async fn dns_tier_apply_record(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let b = body.into_inner(); let result = tokio::task::spawn_blocking(move || { if b.delete { crate::wolfhost::provisioning::dns::delete_record(&b.domain, &b.name, &b.rtype) } else { crate::wolfhost::provisioning::dns::set_record(&b.domain, &b.name, &b.rtype, &b.content, b.ttl) } }).await.unwrap_or_else(|e| Err(e.to_string())); match result { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/settings/login-disabled — set login_disabled on this node (cluster-auth required) pub async fn set_login_disabled(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Accept both cluster auth (from remote dashboard) and session auth (local admin) if let Err(resp) = require_auth(&req, &state) { return resp; } let disabled = body.get("login_disabled").and_then(|v| v.as_bool()).unwrap_or(false); { let mut nodes = state.cluster.nodes_write(); if let Some(node) = nodes.get_mut(&state.cluster.self_id) { node.login_disabled = disabled; } } // Persist to disk crate::agent::ClusterState::save_login_disabled_file(disabled); HttpResponse::Ok().json(serde_json::json!({ "login_disabled": disabled })) } /// POST /api/auth/logout — destroy session pub async fn logout(req: HttpRequest, state: web::Data) -> HttpResponse { if let Some(token) = get_session_token(&req) { state.sessions.destroy(&token); } let mut cookie = Cookie::build("wolfstack_session", "") .path("/") // Match the login cookie's SameSite=Lax so the removal reliably // clears it on a top-level navigation (don't rely on the browser // default, which could tighten to Strict and strand the cookie). .same_site(actix_web::cookie::SameSite::Lax) .finish(); cookie.make_removal(); HttpResponse::Ok() .cookie(cookie) .json(serde_json::json!({ "success": true })) } /// GET /api/auth/check — check if session is valid pub async fn auth_check(req: HttpRequest, state: web::Data) -> HttpResponse { match require_auth(&req, &state) { Ok(username) => HttpResponse::Ok().json(serde_json::json!({ "authenticated": true, "username": username, // Lets the dashboard show the read-only badge up front instead // of the operator discovering it one refused action at a time. "read_only": session_is_read_only(&req, &state), })), Err(_) => HttpResponse::Ok().json(serde_json::json!({ "authenticated": false })), } } // ─── Passkey / WebAuthn (additive — coexists with PAM/WolfStack login) ─── /// Derive (rp_id, origin) from the inbound request's Host header. Strips the /// port for the RP ID; the origin keeps it. Returns an error if the host /// header is missing or unparseable. /// /// Reverse-proxy compatibility: when X-Forwarded-Proto is present we trust /// it for the scheme (and X-Forwarded-Host for the hostname when set), so /// a wolfstack behind nginx/Caddy/Traefik that terminates TLS reports /// `https://...` to webauthn-rs even though wolfstack itself only sees a /// plain HTTP connection. Without this, the browser presents /// origin=https://example.com and we expect origin=http://example.com → /// webauthn-rs rejects with an origin mismatch and the user gets a /// "host header is incorrect for passkeys" failure. fn passkey_rp_origin(req: &HttpRequest, state: &web::Data) -> Result<(String, String), String> { let fwd_host = req.headers().get("X-Forwarded-Host").and_then(|v| v.to_str().ok()); let fwd_proto = req.headers().get("X-Forwarded-Proto").and_then(|v| v.to_str().ok()); derive_passkey_rp_origin(request_host(req), fwd_host, fwd_proto, state.tls_enabled) } /// The host the client addressed: the `Host` header (HTTP/1.1), else the URI /// authority. Over HTTP/2 browsers send the host only as the `:authority` /// pseudo-header, which actix-http stores in the request URI and never turns /// into a `Host` header (actix-http 3.11.2 h2/dispatcher.rs:123 /// `head.uri = parts.uri`; actix-web 4.12.1 info.rs:137-138 uses the same /// Host-then-authority order). Reading only `Host` made passkey ceremonies /// fail with "Missing Host header" on a direct HTTP/2 TLS connection. fn request_host(req: &HttpRequest) -> Option<&str> { req.headers().get("Host").and_then(|v| v.to_str().ok()) .or_else(|| req.uri().authority().map(|a| a.as_str())) } /// Pure function that derives (rp_id, origin) from raw header values. /// Factored out of `passkey_rp_origin` so it's unit-testable without /// constructing an HttpRequest + full AppState. Behaviour: /// /// - Host comes from X-Forwarded-Host first (reverse proxy preserves original /// client Host here), falling back to the Host header. /// - Multi-hop proxies produce comma-separated values — take the first entry, /// which is the original client-facing value. /// - Scheme comes from X-Forwarded-Proto when present and valid (http|https), /// otherwise from the local TLS state. /// - rp_id is the host with the port stripped; origin keeps the port. pub fn derive_passkey_rp_origin( host: Option<&str>, fwd_host: Option<&str>, fwd_proto: Option<&str>, tls_enabled: bool, ) -> Result<(String, String), String> { let host_hdr = fwd_host .filter(|s| !s.is_empty()) .or(host) .ok_or_else(|| "Missing Host header".to_string())?; let host_hdr = host_hdr.split(',').next().unwrap_or("").trim(); if host_hdr.is_empty() { return Err("Missing Host header".to_string()); } let host_no_port = match host_hdr.rsplit_once(':') { Some((h, p)) if !h.is_empty() && p.chars().all(|c| c.is_ascii_digit()) => h, _ => host_hdr, }; let scheme = fwd_proto .map(|s| s.split(',').next().unwrap_or("").trim()) .filter(|s| *s == "http" || *s == "https") .map(|s| s.to_string()) .unwrap_or_else(|| if tls_enabled { "https".into() } else { "http".into() }); let origin = format!("{}://{}", scheme, host_hdr); Ok((host_no_port.to_string(), origin)) } #[derive(Deserialize)] pub struct PasskeyRegisterStartRequest { #[serde(default)] pub label: String, } /// POST /api/auth/passkey/register/start — issue a registration challenge for the /// currently-logged-in user. Requires an existing session. pub async fn passkey_register_start(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if username == "cluster-node" { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Inter-node calls cannot register passkeys" })); } let (rp_id, origin) = match passkey_rp_origin(&req, &state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let display_name = if body.label.is_empty() { username.as_str() } else { body.label.as_str() }; let config = crate::auth::webauthn::WebAuthnConfig::load(); match crate::auth::webauthn::start_registration(&config, &rp_id, &origin, &username, display_name) { Ok((challenge, ceremony_id)) => HttpResponse::Ok().json(serde_json::json!({ "challenge": challenge, "ceremony_id": ceremony_id, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct PasskeyRegisterFinishRequest { pub ceremony_id: String, #[serde(default)] pub label: String, pub response: serde_json::Value, } /// POST /api/auth/passkey/register/finish — verify the attestation and persist the credential. pub async fn passkey_register_finish(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if username == "cluster-node" { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Inter-node calls cannot register passkeys" })); } let (rp_id, origin) = match passkey_rp_origin(&req, &state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let label = if body.label.is_empty() { "Passkey".to_string() } else { body.label.clone() }; let mut config = crate::auth::webauthn::WebAuthnConfig::load(); match crate::auth::webauthn::finish_registration(&mut config, &rp_id, &origin, &body.ceremony_id, &username, &label, &body.response) { Ok(stored) => HttpResponse::Ok().json(serde_json::json!({ "credential_id": stored.credential_id, "label": stored.label, "registered_at": stored.registered_at, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/auth/passkey/available — anonymous lightweight probe used by the /// login page to decide whether to render the "Sign in with passkey" button. /// Returns `{available: bool}` without creating any ceremony state. pub async fn passkey_available(req: HttpRequest, state: web::Data) -> HttpResponse { let config = crate::auth::webauthn::WebAuthnConfig::load(); if config.credentials.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "available": false })); } // Verify the request hostname can actually do WebAuthn — bare-IP // origins will fail at registration/auth time, so don't pretend // they can sign in. let hostname_ok = match passkey_rp_origin(&req, &state) { Ok((rp_id, _)) => rp_id.parse::().is_err(), Err(_) => false, }; HttpResponse::Ok().json(serde_json::json!({ "available": hostname_ok })) } #[derive(Deserialize, Default)] pub struct PasskeyLoginStartRequest { /// Optional. When set and the user has passkeys, the challenge lists /// their credential IDs so non-discoverable passkeys can sign in. #[serde(default)] pub username: String, } /// POST /api/auth/passkey/login/start — issue a discoverable-credential /// challenge, or a username-scoped one when `username` is given. /// Anonymous endpoint — does NOT require a session. pub async fn passkey_login_start(req: HttpRequest, state: web::Data, body: Option>) -> HttpResponse { // If passkey login is unconfigured (no credentials registered) return 404 // so the frontend can hide the "Sign in with passkey" button quickly. let config = crate::auth::webauthn::WebAuthnConfig::load(); if config.credentials.is_empty() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "No passkeys registered on this server" })); } // Check rate limit on this IP — same budget as the password login. // canonical_ip_str: see login() — dual-stack [::] reports mapped v4. let client_ip = crate::netaddr::canonical_ip_str( req.connection_info().peer_addr().unwrap_or("unknown")).into_owned(); if state.login_limiter.is_locked_out(&client_ip) { return HttpResponse::TooManyRequests().json(serde_json::json!({ "error": "Too many failed login attempts. Please try again later." })); } let (rp_id, origin) = match passkey_rp_origin(&req, &state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let body = body.map(|b| b.into_inner()).unwrap_or_default(); let username = body.username.trim(); let username = (!username.is_empty()).then_some(username); match crate::auth::webauthn::start_authentication(&config, &rp_id, &origin, username) { Ok((challenge, ceremony_id)) => HttpResponse::Ok().json(serde_json::json!({ "challenge": challenge, "ceremony_id": ceremony_id, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct PasskeyLoginFinishRequest { pub ceremony_id: String, pub response: serde_json::Value, } /// POST /api/auth/passkey/login/finish — verify the assertion, create a session, set cookie. /// Anonymous endpoint. pub async fn passkey_login_finish(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // canonical_ip_str: see login() — dual-stack [::] reports mapped v4. let client_ip = crate::netaddr::canonical_ip_str( req.connection_info().peer_addr().unwrap_or("unknown")).into_owned(); if state.login_limiter.is_locked_out(&client_ip) { return HttpResponse::TooManyRequests().json(serde_json::json!({ "error": "Too many failed login attempts. Please try again later." })); } // Same direct-login-disabled check the password endpoint does. { let nodes = state.cluster.nodes_read(); if let Some(self_node) = nodes.get(&state.cluster.self_id) && self_node.login_disabled { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Direct login is disabled on this server. Access it via the primary dashboard." })); } } let (rp_id, origin) = match passkey_rp_origin(&req, &state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let mut config = crate::auth::webauthn::WebAuthnConfig::load(); match crate::auth::webauthn::finish_authentication(&mut config, &rp_id, &origin, &body.ceremony_id, &body.response) { Ok(username) => { state.login_limiter.clear(&client_ip); crate::auth::record_admin_ip(&client_ip); // A passkey is bound to a username; if that is a WolfStack-store // user its role applies, otherwise it is a Linux account (full). let read_only = crate::auth::users::UserStore::load() .find(&username) .map(|u| crate::auth::role_is_read_only(&u.role)) .unwrap_or(false); let token = state.sessions.create_session(&username, read_only); let mut cookie = Cookie::build("wolfstack_session", &token) .path("/") .http_only(true) // Lax, not Strict: Strict withholds the session cookie on // top-level navigations/redirects, which broke login on // Microsoft Edge (stricter tracking-prevention than Chrome) — // users authenticated then immediately appeared logged out. // Lax still blocks cross-site POSTs (CSRF) for this same-origin SPA. .same_site(actix_web::cookie::SameSite::Lax) .max_age(actix_web::cookie::time::Duration::hours(8)) .finish(); if state.tls_enabled { cookie.set_secure(true); } HttpResponse::Ok() .cookie(cookie) .json(serde_json::json!({ "success": true, "username": username })) } Err(e) => { state.login_limiter.record_failure(&client_ip); HttpResponse::Unauthorized().json(serde_json::json!({ "success": false, "error": e })) } } } /// GET /api/auth/passkeys — list the current user's registered passkeys. pub async fn passkey_list(req: HttpRequest, state: web::Data) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if username == "cluster-node" { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Inter-node calls cannot list passkeys" })); } let config = crate::auth::webauthn::WebAuthnConfig::load(); let creds = crate::auth::webauthn::list_credentials(&config, &username); let out: Vec = creds.iter().map(|c| serde_json::json!({ "credential_id": c.credential_id, "label": c.label, "registered_at": c.registered_at, "last_used_at": c.last_used_at, })).collect(); HttpResponse::Ok().json(serde_json::json!({ "passkeys": out })) } /// DELETE /api/auth/passkeys/{id} — remove a passkey owned by the current user. pub async fn passkey_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if username == "cluster-node" { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Inter-node calls cannot delete passkeys" })); } let credential_id = path.into_inner(); let mut config = crate::auth::webauthn::WebAuthnConfig::load(); // Ownership check — only the owning user can delete their own passkeys. let owns = config.credentials.iter().any(|c| c.credential_id == credential_id && c.username == username); if !owns { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Passkey not found" })); } match crate::auth::webauthn::remove_credential(&mut config, &credential_id) { Ok(true) => HttpResponse::Ok().json(serde_json::json!({ "removed": true })), Ok(false) => HttpResponse::NotFound().json(serde_json::json!({ "error": "Passkey not found" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Threat Intelligence (WolfRouter integration) ─── /// Helper: best-effort extraction of the requesting client's IP. Used as a /// transient exemption so an admin can't accidentally lock themselves out /// of their own dashboard if their public IP appears on a feed. fn ti_request_client_ip(req: &HttpRequest) -> Vec { // ConnectionInfo::peer_addr() is already the bare IP — actix builds // it as `req.peer_addr.map(|addr| addr.ip().to_string())` // (actix-web-4.13.0/src/info.rs:146). The old rsplit_once(':') here // assumed "ip:port" and silently truncated IPv6 peers to // "2001:db8:"-style garbage, so the safe-filter compare never // matched a v6 client. canonical_ip_str: a dual-stack [::] listener // reports v4 admins as ::ffff:a.b.c.d, which would miss the v4 // safe-filter entry. let ip = crate::netaddr::canonical_ip_str( req.connection_info().peer_addr().unwrap_or("")).into_owned(); if ip.is_empty() { Vec::new() } else { vec![ip] } } /// Per-peer outcome for a cluster-wide threat-intel operation (config /// propagation, ipset install, pause/resume). Surfaced back to the /// frontend so the operator sees exactly which nodes diverged from the /// requested state instead of trusting a fire-and-forget warning log. #[derive(serde::Serialize, Clone, Debug)] pub struct TiPeerOpResult { pub hostname: String, pub address: String, pub ok: bool, pub error: Option, } /// Normalise a cluster name for comparison. Nodes without an explicit /// `cluster_name` (legacy single-cluster installs, freshly-onboarded /// nodes) fall under the "WolfStack" default. Same normalisation rule /// the cluster-status endpoint uses so the peer-filter agrees with /// what the operator sees in the cluster status table. fn ti_normalize_cluster(name: &str) -> String { if name.is_empty() { "WolfStack".to_string() } else { name.to_string() } } /// Extract the target cluster name from `?cluster=` on a threat-intel /// request. Defaults to the bastion's own cluster_name when missing — /// preserves single-cluster behaviour for installs that haven't named /// their cluster yet. fn ti_target_cluster(req: &HttpRequest, state: &web::Data) -> String { if let Some(q) = req.uri().query() { for pair in q.split('&') { if let Some(rest) = pair.strip_prefix("cluster=") && let Ok(decoded) = urlencoding::decode(rest) { let val = decoded.into_owned(); if !val.is_empty() { return val; } } } } state.cluster.get_self_cluster_name() } /// True when `target` matches the bastion's own cluster — used by every /// threat-intel handler to decide whether to (a) load/save the default /// config file vs a per-cluster file, and (b) actually apply kernel /// rules locally vs only update on-disk + propagated state. The /// normalisation rule must match `ti_normalize_cluster` so cluster /// identity is consistent across endpoints. fn ti_is_local_cluster(state: &web::Data, target: &str) -> bool { ti_normalize_cluster(target) == ti_normalize_cluster(state.cluster.get_self_cluster_name().as_str()) } /// On-disk slug for a cluster. Empty for the bastion's own cluster /// (uses legacy `threat-intel.json` for backward compat); otherwise /// the normalised cluster name. This is what the threat_intel module /// expects as its `cluster` parameter — keeping the mapping in one /// place stops the handlers and the propagation code from drifting. fn ti_storage_cluster(state: &web::Data, target: &str) -> String { if ti_is_local_cluster(state, target) { String::new() } else { ti_normalize_cluster(target) } } /// Fan out an `ipset` install request to every online WolfStack peer in /// parallel and await the results. Used when the local admin flips /// Threat Intel to enforce mode — peers need ipset present before they /// can apply kernel rules. Per-peer timeout is 90 seconds (apt/dnf can /// genuinely take that long); each peer runs concurrently so total wait /// is bounded by the slowest peer, not the sum. /// /// Skips: this node, offline nodes, non-wolfstack nodes (Proxmox-only /// entries can't install packages). /// /// Returns one [`TiPeerOpResult`] per attempted peer. The caller — the /// HTTP handler that triggered the enforcement change — includes these /// in its response so the UI can name the failing nodes. async fn ti_install_ipset_on_peers(state: &web::Data, target_cluster: &str) -> Vec { let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let self_id = state.cluster.self_id.clone(); // Threat Intel is per-cluster. Fan out to peers in the TARGET // cluster (the one the operator is modifying), not the bastion's // own cluster — without this scope, the bastion would push ipset // installs to every cluster it manages, including ones whose // operators haven't enabled threat-intel. let target = ti_normalize_cluster(target_cluster); let peers: Vec<(String, String, u16)> = nodes.iter() .filter(|n| !n.is_self && n.id != self_id && n.online && n.node_type == "wolfstack" && ti_normalize_cluster(n.cluster_name.as_deref().unwrap_or("")) == target) .map(|n| (n.hostname.clone(), n.address.clone(), n.port)) .collect(); if peers.is_empty() { return Vec::new(); } let client = &*API_HTTP_CLIENT; let body = serde_json::json!({ "package": "ipset" }); let mut futures = Vec::with_capacity(peers.len()); for (hostname, address, port) in peers { let secret = secret.clone(); let client = client.clone(); let body = body.clone(); futures.push(async move { let urls = build_node_urls(&address, port, "/api/system/install-package"); for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(90)) .peer_auth(&secret) .json(&body) .send() .await { Ok(resp) if resp.status().is_success() => { match resp.json::().await { Ok(data) => { let ok = data.get("success").and_then(|v| v.as_bool()).unwrap_or(false); let msg = data.get("message").and_then(|v| v.as_str()) .or_else(|| data.get("error").and_then(|v| v.as_str())) .unwrap_or("(no message)").to_string(); if ok { tracing::info!("threat-intel: ipset installed on peer '{}' ({}): {}", hostname, address, msg); return TiPeerOpResult { hostname, address, ok: true, error: None }; } tracing::warn!("threat-intel: ipset install on peer '{}' ({}) reported failure: {}", hostname, address, msg); return TiPeerOpResult { hostname, address, ok: false, error: Some(msg) }; } Err(e) => { return TiPeerOpResult { hostname, address, ok: false, error: Some(format!("install response unparseable: {}", e)), }; } } } Ok(resp) => { let status = resp.status(); let _ = resp.bytes().await; tracing::warn!("threat-intel: ipset install on peer '{}' ({}) returned HTTP {}", hostname, address, status); return TiPeerOpResult { hostname, address, ok: false, error: Some(format!("HTTP {}", status)), }; } Err(_) => continue, } } tracing::warn!("threat-intel: could not reach peer '{}' ({}) for ipset install", hostname, address); TiPeerOpResult { hostname, address, ok: false, error: Some("unreachable".into()), } }); } futures::future::join_all(futures).await } /// Push the local Threat Intel config to every online WolfStack peer /// in parallel and await the results. Peers receive the unmasked config /// (real API keys, not "***") so their own scheduler can actually fetch /// feeds. Per-peer timeout 30s; nodes run concurrently so the call /// completes as soon as the slowest peer responds. /// /// Cycle-breaker: peers that receive this call have caller == "cluster-node" /// in their PATCH handler, which skips the re-propagation step. /// /// Returns one [`TiPeerOpResult`] per peer attempted. The caller surfaces /// these so the UI can name nodes that didn't apply the change — without /// this, a peer in a divergent state was invisible to the operator. async fn ti_propagate_config_to_peers(state: &web::Data, target_cluster: &str) -> Vec { let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let self_id = state.cluster.self_id.clone(); // Fan out to peers in the TARGET cluster only — see comment on // ti_install_ipset_on_peers. Each peer in the target cluster // stores the config as its own (default-slot) file because, from // its own perspective, the target cluster IS its cluster. let target = ti_normalize_cluster(target_cluster); let peers: Vec<(String, String, u16)> = nodes.iter() .filter(|n| !n.is_self && n.id != self_id && n.online && n.node_type == "wolfstack" && ti_normalize_cluster(n.cluster_name.as_deref().unwrap_or("")) == target) .map(|n| (n.hostname.clone(), n.address.clone(), n.port)) .collect(); if peers.is_empty() { return Vec::new(); } // Read the unmasked on-disk config for the target cluster and // serialise the full struct. The receiving peer's PATCH handler // will use its own ProviderConfig sentinel logic — including a // real key value (not "***") replaces the on-disk key. let cfg = crate::threat_intel::ThreatIntelConfig::load_for(&ti_storage_cluster(state, target_cluster)); let payload = serde_json::json!({ "enabled": cfg.enabled, "dry_run": cfg.dry_run, "paused": cfg.paused, "refresh_hours": cfg.refresh_hours, "providers": cfg.providers, "allowlist": cfg.allowlist, }); let client = &*API_HTTP_CLIENT; let mut futures = Vec::with_capacity(peers.len()); for (hostname, address, port) in peers { let secret = secret.clone(); let client = client.clone(); let payload = payload.clone(); futures.push(async move { let urls = build_node_urls(&address, port, "/api/threat-intel/config"); for url in &urls { match client.patch(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&secret) .json(&payload) .send() .await { Ok(resp) if resp.status().is_success() => { let _ = resp.bytes().await; tracing::info!("threat-intel: config propagated to peer '{}' ({})", hostname, address); return TiPeerOpResult { hostname, address, ok: true, error: None }; } Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); // Try to extract a structured error from the JSON body. let err_msg = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(|s| s.to_string())) .unwrap_or_else(|| format!("HTTP {}", status)); tracing::warn!("threat-intel: config push to peer '{}' ({}) failed: {}", hostname, address, err_msg); return TiPeerOpResult { hostname, address, ok: false, error: Some(err_msg), }; } Err(_) => continue, } } tracing::warn!("threat-intel: could not reach peer '{}' ({}) for config propagation", hostname, address); TiPeerOpResult { hostname, address, ok: false, error: Some("unreachable".into()), } }); } futures::future::join_all(futures).await } /// Mask API keys before returning a config to the frontend. Empty fields /// stay empty; non-empty fields become "***" so the UI knows a key is /// configured without seeing the value. fn ti_mask_keys(mut cfg: crate::threat_intel::ThreatIntelConfig) -> crate::threat_intel::ThreatIntelConfig { for p in cfg.providers.values_mut() { if !p.api_key.is_empty() { p.api_key = "***".to_string(); } } cfg } /// GET /api/threat-intel/config — return the persisted config (API keys masked). /// `?cluster=NAME` selects which cluster's config to return; default is /// the bastion's own cluster. Peers (cluster-node auth) always read /// their own config slot. pub async fn threat_intel_get_config(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let storage_slug = if from_peer { String::new() } else { let target = ti_target_cluster(&req, &state); ti_storage_cluster(&state, &target) }; let cfg = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); HttpResponse::Ok().json(ti_mask_keys(cfg)) } #[derive(Deserialize)] pub struct ThreatIntelPatchRequest { #[serde(default)] pub enabled: Option, #[serde(default)] pub dry_run: Option, #[serde(default)] pub paused: Option, #[serde(default)] pub refresh_hours: Option, #[serde(default)] pub providers: Option>, #[serde(default)] pub allowlist: Option>, } /// PATCH /api/threat-intel/config — partial update. If the enabled / dry_run / /// paused triplet changes, runs `apply_state_change()` to make the kernel /// state catch up. /// /// API key sentinel: a provider value of `"***"` means "don't change", /// preserving the existing on-disk key. Anything else (including empty /// string to clear) is used verbatim. pub async fn threat_intel_patch_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Cycle-breaker: when a peer receives a propagated config push, the // caller is "cluster-node" (X-WolfStack-Secret auth). Don't re-propagate // back out — the originating bastion is already fanning to every node. // Peers always treat the propagated config as THEIR OWN cluster's // config (cluster slug = "") regardless of any ?cluster= the bastion // tacked on, since from the peer's perspective the target IS their // cluster. Operator-driven calls use the requested target cluster. let from_peer = caller == "cluster-node"; let target_cluster = ti_target_cluster(&req, &state); let storage_slug = if from_peer { String::new() } else { ti_storage_cluster(&state, &target_cluster) }; let is_local_kernel = from_peer || ti_is_local_cluster(&state, &target_cluster); let mut cfg = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); let prev_enforcement = crate::threat_intel::enforcement_active(&cfg); if let Some(v) = body.enabled { cfg.enabled = v; } if let Some(v) = body.dry_run { cfg.dry_run = v; } if let Some(v) = body.paused { cfg.paused = v; } if let Some(v) = body.refresh_hours { // Clamp at the API boundary too so the saved config matches what the // scheduler will actually use. cfg.refresh_hours = v.clamp(1, 168); } if let Some(allowlist) = &body.allowlist { cfg.allowlist = allowlist.clone(); } if let Some(providers) = &body.providers { for (id, incoming) in providers.iter() { let entry = cfg.providers.entry(id.clone()).or_insert_with(|| crate::threat_intel::ProviderConfig { enabled: false, api_key: String::new(), url_override: String::new(), }); entry.enabled = incoming.enabled; // Sentinel "***" means "don't change". Anything else replaces. if incoming.api_key != "***" { entry.api_key = incoming.api_key.clone(); } entry.url_override = incoming.url_override.clone(); } } if let Err(e) = cfg.save_for(&storage_slug) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let new_enforcement = crate::threat_intel::enforcement_active(&cfg); let mut apply_error: Option = None; let mut ipset_install_results: Vec = Vec::new(); if new_enforcement != prev_enforcement { // The kernel state needs to catch up. Run on a blocking thread — // apply_state_change_for shells out to ipset/iptables-restore // (only when is_local_kernel; otherwise it just refreshes the // cached `applied` flag for the target cluster). let slug_for_apply = storage_slug.clone(); match tokio::task::spawn_blocking(move || crate::threat_intel::apply_state_change_for(&slug_for_apply, is_local_kernel)).await { Ok(Ok(())) => { // Enforcement just activated for the target cluster. // Fan out an ipset install to peers in THAT cluster so // they can apply kernel rules themselves. if new_enforcement && !from_peer { ipset_install_results = ti_install_ipset_on_peers(&state, &target_cluster).await; } } Ok(Err(e)) => apply_error = Some(e), Err(e) => apply_error = Some(format!("apply task panicked: {}", e)), } // If the apply failed, roll the config back so on-disk state matches kernel state. if apply_error.is_some() { let mut rolled = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); rolled.enabled = false; rolled.dry_run = true; rolled.paused = false; let _ = rolled.save_for(&storage_slug); } } if let Some(e) = apply_error { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Config saved, but enforcement could not be activated: {}. Configuration was rolled back to a safe state.", e), })); } // Cluster-wide propagation. Peers process the same PATCH (with // caller=cluster-node) which short-circuits their own re-propagation // so we won't loop. Awaited so the response can name peers that // failed to apply the change — see comment on ti_propagate_config_to_peers. let mut propagation_results: Vec = Vec::new(); if !from_peer { propagation_results = ti_propagate_config_to_peers(&state, &target_cluster).await; } HttpResponse::Ok().json(serde_json::json!({ "config": ti_mask_keys(crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug)), "peers": propagation_results, "ipset_install": ipset_install_results, })) } /// POST /api/threat-intel/refresh — trigger an immediate refresh. /// `?cluster=NAME` selects the cluster whose feeds to refresh; default /// is the bastion's own cluster. pub async fn threat_intel_refresh(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = ti_target_cluster(&req, &state); let storage_slug = ti_storage_cluster(&state, &target); let is_local_kernel = ti_is_local_cluster(&state, &target); // Only exempt cluster_node_ips from peers in the TARGET cluster — // unrelated clusters' IPs shouldn't get a free pass. let target_norm = ti_normalize_cluster(&target); let cluster_ips: Vec = state.cluster.get_all_nodes().iter() .filter(|n| ti_normalize_cluster(n.cluster_name.as_deref().unwrap_or("")) == target_norm) .map(|n| n.address.clone()) .filter(|a| match a.parse::() { Ok(ip) => !ip.is_unspecified(), Err(_) => false, }) .collect(); let admin_ip = ti_request_client_ip(&req); let new_state = crate::threat_intel::refresh_all_for(&storage_slug, cluster_ips, admin_ip, is_local_kernel).await; HttpResponse::Ok().json(new_state) } /// POST /api/threat-intel/pause — emergency-off. Drops the kernel rule /// immediately while preserving config + ipset state for a one-click /// resume. Cluster-scoped: `?cluster=NAME` pauses just that cluster. pub async fn threat_intel_pause(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let target = ti_target_cluster(&req, &state); let storage_slug = if from_peer { String::new() } else { ti_storage_cluster(&state, &target) }; let is_local_kernel = from_peer || ti_is_local_cluster(&state, &target); let mut cfg = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); if cfg.paused { return HttpResponse::Ok().json(serde_json::json!({ "paused": true, "no_op": true, "peers": [] })); } cfg.paused = true; if let Err(e) = cfg.save_for(&storage_slug) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let slug_for_apply = storage_slug.clone(); match tokio::task::spawn_blocking(move || crate::threat_intel::apply_state_change_for(&slug_for_apply, is_local_kernel)).await { Ok(Ok(())) => { // Pause is the operator's "emergency off" for THIS cluster. // Propagate to peers in the target cluster only — pausing // cluster A's view shouldn't take cluster B offline. let mut peers: Vec = Vec::new(); if !from_peer { peers = ti_propagate_config_to_peers(&state, &target).await; } HttpResponse::Ok().json(serde_json::json!({ "paused": true, "peers": peers })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("apply task panicked: {}", e) })), } } /// POST /api/threat-intel/resume — undo a pause. Cluster-scoped. pub async fn threat_intel_resume(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let target = ti_target_cluster(&req, &state); let storage_slug = if from_peer { String::new() } else { ti_storage_cluster(&state, &target) }; let is_local_kernel = from_peer || ti_is_local_cluster(&state, &target); let mut cfg = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); if !cfg.paused { return HttpResponse::Ok().json(serde_json::json!({ "paused": false, "no_op": true, "peers": [], "ipset_install": [] })); } cfg.paused = false; if let Err(e) = cfg.save_for(&storage_slug) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let slug_for_apply = storage_slug.clone(); match tokio::task::spawn_blocking(move || crate::threat_intel::apply_state_change_for(&slug_for_apply, is_local_kernel)).await { Ok(Ok(())) => { // If unpausing actually re-activated enforcement (the common // case — pause was the only thing turning it off), make sure // peers in the target cluster have ipset and the same config. let mut ipset_install: Vec = Vec::new(); let mut peers: Vec = Vec::new(); if !from_peer && crate::threat_intel::enforcement_active(&crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug)) { ipset_install = ti_install_ipset_on_peers(&state, &target).await; peers = ti_propagate_config_to_peers(&state, &target).await; } HttpResponse::Ok().json(serde_json::json!({ "paused": false, "peers": peers, "ipset_install": ipset_install, })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("apply task panicked: {}", e) })), } } /// GET /api/threat-intel/status — current state for the UI: per-provider /// fetch status, total blocklist size, applied flag, sample of recently /// added IPs (first 50 of each family — the UI uses these for "preview" /// rendering without shipping 200k entries to the browser). pub async fn threat_intel_status(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let storage_slug = if from_peer { String::new() } else { let target = ti_target_cluster(&req, &state); ti_storage_cluster(&state, &target) }; let snapshot = crate::threat_intel::snapshot_cache_for(&storage_slug); let cfg = crate::threat_intel::ThreatIntelConfig::load_for(&storage_slug); let sample_v4: Vec = snapshot.blocklist_v4.iter().take(50).cloned().collect(); let sample_v6: Vec = snapshot.blocklist_v6.iter().take(50).cloned().collect(); // Annotate self-blacklisted entries with hostnames for the UI banner. // Mapping IP → hostname is best-effort: we look in the cluster node // list. If the mapping fails (IP not in cluster, race during node // removal), the UI just shows "(unknown)" — non-blocking. // // Filter unspecified addresses (0.0.0.0 / ::) at read time too — // covers the in-memory cache when it was populated from a state file // written by an older release before the upstream filter existed. let nodes = state.cluster.get_all_nodes(); let self_blacklisted: Vec = snapshot.self_blacklisted.iter() .filter(|(ip, _)| { match ip.parse::() { Ok(p) => !p.is_unspecified(), Err(_) => false, } }) .map(|(ip, providers)| { let hostname = nodes.iter() .find(|n| n.address == *ip) .map(|n| n.hostname.clone()) .unwrap_or_default(); serde_json::json!({ "ip": ip, "hostname": hostname, "listed_by": providers, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "enabled": cfg.enabled, "dry_run": cfg.dry_run, "paused": cfg.paused, "enforcement_active": crate::threat_intel::enforcement_active(&cfg), "applied": snapshot.applied, "last_refresh_secs": snapshot.last_refresh_secs, "blocklist_size": snapshot.blocklist_size, "blocklist_v4_count": snapshot.blocklist_v4.len(), "blocklist_v6_count": snapshot.blocklist_v6.len(), "sample_v4": sample_v4, "sample_v6": sample_v6, "providers": snapshot.providers, "self_blacklisted": self_blacklisted, "ipset_available": crate::threat_intel::ipset::ipset_available(), "max_blocklist_size": crate::threat_intel::MAX_BLOCKLIST_SIZE, })) } /// GET /api/threat-intel/cluster-status — aggregate Threat Intel status /// across every WolfStack node in the cluster, so the bastion's UI can /// show "node X is enforcing 12k entries, last refresh 5min ago" for /// every peer at once instead of just the local node. /// /// Self status comes from in-memory cache (cheap). Online peers are /// queried in parallel via the inter-node HTTP channel with a 4-second /// timeout each — slow peers don't block the response. Offline / /// non-WolfStack nodes are listed with status: null and a reason. pub async fn threat_intel_cluster_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // WolfRouter (and its Threat Intel tab) is per-cluster — a bastion // managing 5 clusters across 14 servers should NOT see every cluster's // peers lumped into every cluster view. Honour the same `?cluster=NAME` // filter the topology endpoint uses; nameless nodes normalise to // "WolfStack". Caveat (intentional, surfaced via the UI): the actual // ThreatIntelConfig is one global file at /etc/wolfstack/threat-intel.json // — propagation is cluster-wide. Adam Cogswell 2026-04-29: noticed // the status panel was showing all 14 servers regardless of which // cluster's WolfRouter view was open. let cluster_filter = req.uri().query() .and_then(|q| { for pair in q.split('&') { if let Some(rest) = pair.strip_prefix("cluster=") { return urlencoding::decode(rest).ok().map(|s| s.into_owned()); } } None }); let normalize = |n: Option<&str>| -> String { match n { Some(s) if !s.is_empty() => s.to_string(), _ => "WolfStack".into(), } }; let self_cluster_raw = state.cluster.get_self_cluster_name(); let self_cluster_norm = normalize( if self_cluster_raw.is_empty() { None } else { Some(self_cluster_raw.as_str()) } ); let include_self = match &cluster_filter { Some(want) => &self_cluster_norm == want, None => true, }; let all_nodes = state.cluster.get_all_nodes(); let nodes: Vec<_> = all_nodes.into_iter() .filter(|n| { if n.is_self || n.id == state.cluster.self_id { include_self } else { match &cluster_filter { Some(want) => &normalize(n.cluster_name.as_deref()) == want, None => true, } } }) .collect(); let secret = state.cluster_secret.clone(); let self_id = state.cluster.self_id.clone(); // Build the local node's summary up front from the in-memory cache. // Cheap; doesn't do any HTTP. Same shape as the per-peer fetch result // so the aggregator stays uniform. let local_summary = { let cfg = crate::threat_intel::ThreatIntelConfig::load(); let snapshot = crate::threat_intel::snapshot_cache(); serde_json::json!({ "enabled": cfg.enabled, "dry_run": cfg.dry_run, "paused": cfg.paused, "enforcement_active": crate::threat_intel::enforcement_active(&cfg), "applied": snapshot.applied, "last_refresh_secs": snapshot.last_refresh_secs, "blocklist_size": snapshot.blocklist_size, "blocklist_v4_count": snapshot.blocklist_v4.len(), "blocklist_v6_count": snapshot.blocklist_v6.len(), "providers": snapshot.providers, "ipset_available": crate::threat_intel::ipset::ipset_available(), }) }; // Fetch peer statuses concurrently. Each fetch has its own short // timeout; one slow peer doesn't drag the whole aggregation. let client = &*API_HTTP_CLIENT; let mut futures: Vec + Send>>> = Vec::new(); for node in nodes.iter() { if node.is_self || node.id == self_id { // Local entry — emit synchronously. let entry = serde_json::json!({ "id": node.id, "hostname": node.hostname, "address": node.address, "is_self": true, "online": true, "reachable": true, "status": local_summary.clone(), "error": serde_json::Value::Null, }); futures.push(Box::pin(async move { entry })); continue; } if !node.online { let entry = serde_json::json!({ "id": node.id, "hostname": node.hostname, "address": node.address, "is_self": false, "online": false, "reachable": false, "status": serde_json::Value::Null, "error": "Node is offline", }); futures.push(Box::pin(async move { entry })); continue; } if node.node_type != "wolfstack" { let entry = serde_json::json!({ "id": node.id, "hostname": node.hostname, "address": node.address, "is_self": false, "online": node.online, "reachable": false, "status": serde_json::Value::Null, "error": format!("Node type '{}' does not run threat-intel", node.node_type), }); futures.push(Box::pin(async move { entry })); continue; } // Online wolfstack peer — fetch over inter-node. let id = node.id.clone(); let hostname = node.hostname.clone(); let address = node.address.clone(); let port = node.port; let secret = secret.clone(); let client = client.clone(); futures.push(Box::pin(async move { let urls = build_node_urls(&address, port, "/api/threat-intel/status"); for url in &urls { match client.get(url) .timeout(std::time::Duration::from_secs(4)) .peer_auth(&secret) .send().await { Ok(resp) if resp.status().is_success() => { if let Ok(body) = resp.json::().await { return serde_json::json!({ "id": id, "hostname": hostname, "address": address, "is_self": false, "online": true, "reachable": true, "status": body, "error": serde_json::Value::Null, }); } } Ok(resp) => { let code = resp.status(); let _ = resp.bytes().await; return serde_json::json!({ "id": id, "hostname": hostname, "address": address, "is_self": false, "online": true, "reachable": false, "status": serde_json::Value::Null, "error": format!("Peer returned HTTP {}", code), }); } Err(_) => continue, } } serde_json::json!({ "id": id, "hostname": hostname, "address": address, "is_self": false, "online": true, "reachable": false, "status": serde_json::Value::Null, "error": "Could not reach peer (timeout / network)", }) })); } let results = futures::future::join_all(futures).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// GET /api/threat-intel/lookup/{ip} — is this IP currently blocked, and which feed CIDRs match? /// `?cluster=NAME` picks which cluster's blocklist to check against; /// default is the bastion's own. pub async fn threat_intel_lookup(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let ip = path.into_inner(); if ip.parse::().is_err() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a valid IP address" })); } let storage_slug = if from_peer { String::new() } else { let target = ti_target_cluster(&req, &state); ti_storage_cluster(&state, &target) }; let matches = crate::threat_intel::lookup_ip_for(&storage_slug, &ip); HttpResponse::Ok().json(serde_json::json!({ "ip": ip, "blocked": !matches.is_empty(), "matches": matches, })) } // ─── Password Reset API (no auth required) ─── /// GET /api/auth/smtp-configured — check if SMTP is configured (controls "Lost Password" visibility) pub async fn smtp_configured() -> HttpResponse { let config = crate::ai::AiConfig::load(); // Host is the only hard requirement — auth (user/pass) is optional for // unauthenticated relays, consistent with the send path and abuse-report gate. let configured = !config.smtp_host.is_empty(); HttpResponse::Ok().json(serde_json::json!({ "smtp_configured": configured, "version": env!("CARGO_PKG_VERSION") })) } /// POST /api/auth/forgot-password — send a password reset email pub async fn forgot_password(state: web::Data, body: web::Json) -> HttpResponse { let username = body["username"].as_str().unwrap_or("").trim(); if username.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Username is required"})); } // Rate limit by IP is already handled at the login level, but let's not leak user existence. // Always return success to prevent user enumeration. let generic_ok = HttpResponse::Ok().json(serde_json::json!({ "success": true, "message": "If an account with that username exists and has an email address, a reset link has been sent." })); // Look up the WolfStack user. Every no-email branch below returns the // same generic_ok to the CLIENT (anti-enumeration) but logs WHY server- // side — "reset doesn't work" is undiagnosable otherwise (Paul, // 2026-07-13: reset flow showed 'sent' but no email ever arrived). let store = crate::auth::users::UserStore::load(); let user = match store.find(username) { Some(u) => u.clone(), None => { tracing::warn!( "password reset requested for '{}' — no such WolfStack user \ (system/Linux accounts cannot reset by email; no email was sent)", username ); return generic_ok; } }; if user.email.is_empty() { tracing::warn!( "password reset requested for '{}' — user has no email address \ set (Settings → Users), no email was sent", username ); return generic_ok; } // Check SMTP is configured. Host is the only hard requirement — auth is // optional (unauthenticated relays). If the From/host turn out unsendable we // still return the generic response below to avoid leaking account state. let config = crate::ai::AiConfig::load(); if config.smtp_host.is_empty() { tracing::warn!( "password reset requested for '{}' — SMTP is not configured \ (Settings → AI & Email), no email was sent", username ); return generic_ok; } // Create reset token let token = state.password_reset_tokens.create(username); // Send the email let subject = "WolfStack — Password Reset"; let body_text = format!( "A password reset was requested for your WolfStack account '{}'.\n\n\ Your reset code is:\n\n {}\n\n\ Enter this code on the login page to set a new password.\n\ This code expires in 30 minutes.\n\n\ If you did not request this, you can safely ignore this email.", username, token ); // To the USER's address — send_alert_email would mail the site-wide // alert inbox instead (wrong recipient + code disclosure). match crate::ai::send_text_email(&config, &user.email, "WolfStack", subject, &body_text) { Ok(()) => generic_ok, Err(e) => { tracing::warn!("Failed to send password reset email: {}", e); generic_ok // Don't leak SMTP errors } } } /// POST /api/auth/reset-password — validate reset token and set new password pub async fn reset_password(state: web::Data, body: web::Json) -> HttpResponse { let token = body["token"].as_str().unwrap_or("").trim(); let new_password = body["password"].as_str().unwrap_or(""); if token.is_empty() || new_password.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Token and new password are required"})); } if new_password.len() < 6 { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Password must be at least 6 characters"})); } // Validate and consume the token let username = match state.password_reset_tokens.validate_and_consume(token) { Some(u) => u, None => return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid or expired reset code"})), }; // Hash the new password and update the user let password_hash = match crate::auth::users::hash_password(new_password) { Ok(h) => h, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), }; let mut store = crate::auth::users::UserStore::load(); if let Some(user) = store.find_mut(&username) { user.password_hash = password_hash; if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true, "message": "Password has been reset. You can now log in."})) } else { HttpResponse::BadRequest().json(serde_json::json!({"error": "User no longer exists"})) } } // ─── User Management API ─── /// GET /api/auth/config — get auth configuration pub async fn get_auth_config(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::auth::users::AuthConfig::load()) } /// POST /api/auth/config — update auth configuration pub async fn save_auth_config(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // save() stamps a fresh version; trigger an immediate replication push. match body.into_inner().save() { Ok(()) => { trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// GET /api/auth/users — list all WolfStack users (hides password hashes and TOTP secrets) pub async fn list_users(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Admins see the full list; everyone else sees only their own // entry — a viewer session must not enumerate other users' email // addresses and 2FA posture (information disclosure). let caller_is_admin = crate::auth::session_user_is_admin(&caller); let store = crate::auth::users::UserStore::load(); let users: Vec = store.users.iter() .filter(|u| caller_is_admin || u.username == caller) .map(|u| { serde_json::json!({ "username": u.username, "role": u.role, "display_name": u.display_name, "email": u.email, "totp_enabled": u.totp_enabled, "created_at": u.created_at, }) }).collect(); HttpResponse::Ok().json(users) } /// POST /api/auth/users — create a new WolfStack user pub async fn create_user(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if let Err(resp) = require_admin(&caller) { return resp; } let username = body["username"].as_str().unwrap_or("").trim().to_string(); let password = body["password"].as_str().unwrap_or(""); let role = body["role"].as_str().unwrap_or("admin").to_string(); let display_name = body["display_name"].as_str().unwrap_or("").to_string(); if username.is_empty() || password.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Username and password required"})); } // Only the two documented roles. Any other string would be stored and // then treated as read-only by role_is_read_only — better to refuse a // typo up front than to create an account that silently cannot act. if role != "admin" && role != "viewer" { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Role must be 'admin' or 'viewer'"})); } if !crate::auth::is_safe_name(&username) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid username — use alphanumeric, dash, underscore only"})); } let password_hash = match crate::auth::users::hash_password(password) { Ok(h) => h, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), }; let email = body["email"].as_str().unwrap_or("").trim().to_string(); // Same rules as change_user_email — an unvalidated stored address // would become an SMTP header-injection vector via the reset email. if let Err(e) = validate_email_loose(&email) { return HttpResponse::BadRequest().json(serde_json::json!({"error": e})); } // Allowed clusters — comma-free list from the create form. Empty = // see-everything (matches the existing default for legacy users); // for restricted team members the operator fills this in. The // field is enterprise-only; on non-enterprise installs the UI // doesn't render it and we discard any value posted anyway so a // bad-actor admin can't pre-seed restrictions that then get // enforced. "Enterprise" = any valid license. let allowed_clusters: Vec = if crate::compat::platform_ready() { body.get("allowed_clusters") .and_then(|v| v.as_array()) .map(|arr| arr.iter().filter_map(|x| x.as_str().map(|s| s.trim().to_string())) .filter(|s| !s.is_empty()).collect()) .unwrap_or_default() } else { Vec::new() }; let user = crate::auth::users::WolfUser { username: username.clone(), password_hash, totp_secret: String::new(), totp_enabled: false, role, display_name, email, created_at: chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(), allowed_clusters, }; let mut store = crate::auth::users::UserStore::load(); match store.add(user) { Ok(()) => { // Replicate the new user to the rest of the fleet so it can log in // on any node. trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true, "username": username})) } Err(e) => HttpResponse::Conflict().json(serde_json::json!({"error": e})), } } /// DELETE /api/auth/users/{username} — delete a WolfStack user pub async fn delete_user(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if let Err(resp) = require_admin(&caller) { return resp; } let username = path.into_inner(); let mut store = crate::auth::users::UserStore::load(); match store.remove(&username) { Ok(()) => { // End the user's MCP grants on this node now (other nodes refuse // them on the next request: the account no longer resolves). let u = username.clone(); match web::block(move || crate::mcp::OAUTH.revoke_user(&u)).await { Ok(Ok(_)) => {} Ok(Err(e)) => tracing::warn!("mcp: could not revoke grants of deleted user '{}': {}", username, e), Err(e) => tracing::warn!("mcp: revoke task for deleted user '{}' failed: {}", username, e), } // Propagate the deletion (newer version) so it isn't undone by a // peer's stale copy on the next sweep. trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::NotFound().json(serde_json::json!({"error": e})), } } /// Admin-or-self gate for per-user mutation endpoints (password, /// email, 2FA) — a viewer-role session must not be able to repoint /// another user's credentials (privilege escalation → account /// takeover). Admin-ness via `auth::session_user_is_admin`, which /// also recognises privileged LINUX sessions (root / sudo / wheel) — /// the bootstrap path that manages WolfStack users in the first place. fn require_admin_or_self(caller: &str, target: &str) -> Result<(), HttpResponse> { if caller == target || crate::auth::session_user_is_admin(caller) { Ok(()) } else { Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Only admin users can modify other users" }))) } } /// Admin-only gate (user create / delete). fn require_admin(caller: &str) -> Result<(), HttpResponse> { if crate::auth::session_user_is_admin(caller) { Ok(()) } else { Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Only admin users can manage users" }))) } } /// POST /api/auth/users/{username}/password — change password pub async fn change_user_password(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let username = path.into_inner(); if let Err(resp) = require_admin_or_self(&caller, &username) { return resp; } let new_password = body["password"].as_str().unwrap_or(""); if new_password.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Password required"})); } let password_hash = match crate::auth::users::hash_password(new_password) { Ok(h) => h, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), }; let mut store = crate::auth::users::UserStore::load(); match store.find_mut(&username) { Some(user) => { user.password_hash = password_hash; match store.save() { Ok(()) => { // Outstanding reset codes die with the old password. state.password_reset_tokens.invalidate_user(&username); // So do MCP grants (cluster-wide via the credential // fingerprint; here immediately). let u = username.clone(); match web::block(move || crate::mcp::OAUTH.revoke_user(&u)).await { Ok(Ok(_)) => {} Ok(Err(e)) => tracing::warn!("mcp: could not revoke grants of '{}' after password change: {}", username, e), Err(e) => tracing::warn!("mcp: revoke task for '{}' failed: {}", username, e), } trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } None => HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})), } } /// POST /api/auth/users/{username}/email — set (or clear) the email /// address used by the forgot-password flow. Until now the WolfUser /// email field existed but nothing could write it, so password reset /// silently had nobody to mail (Paul, 2026-07-13). Empty email = clear /// (reset-by-email off for that user). pub async fn change_user_email(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let username = path.into_inner(); if let Err(resp) = require_admin_or_self(&caller, &username) { return resp; } let email = body["email"].as_str().unwrap_or("").trim().to_string(); if let Err(e) = validate_email_loose(&email) { return HttpResponse::BadRequest().json(serde_json::json!({"error": e})); } let mut store = crate::auth::users::UserStore::load(); match store.find_mut(&username) { Some(user) => { user.email = email; match store.save() { Ok(()) => { // A reset code that went to the OLD address must not // stay redeemable. state.password_reset_tokens.invalidate_user(&username); trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } None => HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})), } } /// Light-touch email validation shared by user create + email update — /// enough to catch typos and block header-injection (whitespace incl. /// CR/LF) without rejecting valid unusual addresses. Empty = allowed /// (clears the address / opts out of reset-by-email). fn validate_email_loose(email: &str) -> Result<(), String> { if email.is_empty() { return Ok(()); } let parts: Vec<&str> = email.split('@').collect(); if email.len() > 254 || email.chars().any(|c| c.is_whitespace()) || parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() { return Err("That doesn't look like a valid email address".to_string()); } Ok(()) } /// POST /api/auth/users/{username}/2fa/setup — generate a new TOTP secret (not yet confirmed) pub async fn setup_2fa(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let username = path.into_inner(); if let Err(resp) = require_admin_or_self(&caller, &username) { return resp; } let store = crate::auth::users::UserStore::load(); if store.find(&username).is_none() { return HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})); } let secret = crate::auth::users::generate_totp_secret(); let uri = crate::auth::users::totp_uri(&secret, &username); // None only if the URI overflows a QR code; the dialog then falls back // to the manual entry key, which is always shown. let qr_svg = match crate::auth::users::totp_qr_svg(&uri) { Ok(svg) => Some(svg), Err(e) => { tracing::warn!("2FA setup for {}: QR render failed: {}", username, e); None } }; HttpResponse::Ok().json(serde_json::json!({ "secret": secret, "uri": uri, "qr_svg": qr_svg, })) } /// POST /api/auth/users/{username}/2fa/confirm — verify a TOTP code and enable 2FA pub async fn confirm_2fa(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let username = path.into_inner(); if let Err(resp) = require_admin_or_self(&caller, &username) { return resp; } let code = body["code"].as_str().unwrap_or(""); let secret = body["secret"].as_str().unwrap_or(""); if code.is_empty() || secret.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Code and secret required"})); } // Verify the code matches the secret before enabling if !crate::auth::users::verify_totp(secret, code) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid code — check your authenticator app and try again"})); } let mut store = crate::auth::users::UserStore::load(); match store.find_mut(&username) { Some(user) => { user.totp_secret = secret.to_string(); user.totp_enabled = true; match store.save() { Ok(()) => { trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } None => HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})), } } /// PUT /api/auth/users/{username}/clusters — update which clusters /// this user is allowed to see. Empty list = all clusters (legacy /// behaviour, admins always pass regardless). Non-empty list = only /// the named clusters show up in /api/nodes responses and related /// per-cluster views. Requires admin auth — we don't let a restricted /// user re-widen their own scope. pub async fn update_user_clusters( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Enterprise-only — any valid license unlocks it, no per-feature // toggle. On a non-enterprise install the route returns 404 (route // invisible, matching the hidden UI — no upgrade leakage). if !crate::compat::platform_ready() { return HttpResponse::NotFound().finish(); } // session_user_is_admin also recognises privileged Linux sessions // (root/sudo/wheel) — the previous store-only lookup rejected them // even though they're the accounts that bootstrap WolfStack users. if !crate::auth::session_user_is_admin(&caller) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Only admin users can change cluster access" })); } let username = path.into_inner(); let new_clusters: Vec = body.get("allowed_clusters") .and_then(|v| v.as_array()) .map(|arr| arr.iter().filter_map(|x| x.as_str().map(|s| s.trim().to_string())) .filter(|s| !s.is_empty()).collect()) .unwrap_or_default(); let mut store = crate::auth::users::UserStore::load(); match store.find_mut(&username) { Some(user) => { user.allowed_clusters = new_clusters.clone(); match store.save() { Ok(()) => { trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true, "username": username, "allowed_clusters": new_clusters, })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } None => HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})), } } /// POST /api/auth/users/{username}/2fa/disable — disable 2FA for a user pub async fn disable_2fa(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let username = path.into_inner(); if let Err(resp) = require_admin_or_self(&caller, &username) { return resp; } let mut store = crate::auth::users::UserStore::load(); match store.find_mut(&username) { Some(user) => { user.totp_secret.clear(); user.totp_enabled = false; match store.save() { Ok(()) => { trigger_control_plane_push(&state); HttpResponse::Ok().json(serde_json::json!({"success": true})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } None => HttpResponse::NotFound().json(serde_json::json!({"error": "User not found"})), } } // ─── Dashboard API ─── /// GET /api/metrics — current system metrics pub async fn get_metrics(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let st = state.into_inner(); let metrics = tokio::task::spawn_blocking(move || { st.monitor.lock().unwrap().collect() }).await.unwrap(); HttpResponse::Ok().json(metrics) } /// GET /api/metrics/history — historical CPU, RAM, disk metrics pub async fn get_metrics_history(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let history = state.metrics_history.lock().unwrap(); HttpResponse::Ok().json(history.get_all()) } /// GET /api/metrics/processes — top CPU and memory consuming processes pub async fn get_top_processes(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let st = state.into_inner(); let (top_cpu, top_mem) = tokio::task::spawn_blocking(move || { st.monitor.lock().unwrap().top_processes(10) }).await.unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "top_cpu": top_cpu, "top_mem": top_mem, })) } /// POST /api/metrics/processes/{pid}/kill — kill a process by PID pub async fn kill_process(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let pid = path.into_inner(); // Safety: refuse to kill PID 1 (init) or PID 0 if pid <= 1 { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Cannot kill system process"})); } let result = std::process::Command::new("kill") .arg(pid.to_string()) .output(); match result { Ok(o) if o.status.success() => { HttpResponse::Ok().json(serde_json::json!({"ok": true, "pid": pid})) } Ok(o) => { let stderr = String::from_utf8_lossy(&o.stderr).to_string(); HttpResponse::Ok().json(serde_json::json!({"ok": false, "error": stderr.trim()})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } // ─── Systemd Services ─── #[derive(Serialize)] struct SystemdService { name: String, description: String, active: String, // "active", "inactive", "failed", etc. sub_state: String, // "running", "dead", "exited", "failed", etc. enabled: String, // "enabled", "disabled", "static", "masked", etc. } /// GET /api/systemd — list systemd services pub async fn list_services(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let services = tokio::task::spawn_blocking(|| { // Use JSON output for reliable parsing (supported by systemd 240+) let output = std::process::Command::new("systemctl") .args(["list-units", "--type=service", "--all", "--no-pager", "--output=json"]) .output(); let mut result = Vec::new(); if let Ok(out) = output && let Ok(units) = serde_json::from_slice::>(&out.stdout) { for u in &units { let name = u["unit"].as_str().unwrap_or("").trim_end_matches(".service").to_string(); if name.is_empty() { continue; } // Skip internal systemd units if name.starts_with("systemd-") { continue; } let active = u["active"].as_str().unwrap_or("").to_string(); let sub = u["sub"].as_str().unwrap_or("").to_string(); let desc = u["description"].as_str().unwrap_or("").to_string(); result.push(SystemdService { name, description: desc, active, sub_state: sub, enabled: String::new(), }); } } // Get enabled/disabled status let enabled_output = std::process::Command::new("systemctl") .args(["list-unit-files", "--type=service", "--no-pager", "--no-legend"]) .output(); if let Ok(out) = enabled_output { let enabled_map: std::collections::HashMap = String::from_utf8_lossy(&out.stdout) .lines() .filter_map(|line| { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() >= 2 { Some((parts[0].trim_end_matches(".service").to_string(), parts[1].to_string())) } else { None } }) .collect(); for svc in &mut result { if let Some(state) = enabled_map.get(&svc.name) { svc.enabled = state.clone(); } } } result }).await.unwrap_or_default(); HttpResponse::Ok().json(services) } #[derive(Deserialize)] pub struct SystemdActionRequest { pub action: String, } /// POST /api/services/{name}/action — start/stop/restart/enable/disable a systemd service pub async fn systemd_service_action(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let action = body.action.clone(); // Validate action if !["start", "stop", "restart", "enable", "disable"].contains(&action.as_str()) { return HttpResponse::BadRequest().json(serde_json::json!({"error": format!("Unknown action: {}", action)})); } // Validate service name (prevent injection) if !name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '@' || c == '.') { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid service name"})); } let svc_name = format!("{}.service", name); let act = action.clone(); let result = tokio::task::spawn_blocking(move || { let output = std::process::Command::new("systemctl") .args([&act, &svc_name]) .output(); match output { Ok(o) => { let stdout = String::from_utf8_lossy(&o.stdout).to_string(); let stderr = String::from_utf8_lossy(&o.stderr).to_string(); (o.status.success(), stdout, stderr) } Err(e) => (false, String::new(), format!("Failed to execute: {}", e)), } }).await.unwrap_or((false, String::new(), "Task failed".to_string())); if result.0 { HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": format!("{} {}", action, name)})) } else { // On failure, also grab the service status/journal for diagnostics let svc_name2 = format!("{}.service", name); let diagnostics = tokio::task::spawn_blocking(move || { let status = std::process::Command::new("systemctl") .args(["status", &svc_name2, "--no-pager", "-l"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) .unwrap_or_default(); let journal = std::process::Command::new("journalctl") .args(["-u", &svc_name2, "--no-pager", "-n", "30", "--no-hostname"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) .unwrap_or_default(); (status, journal) }).await.unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": result.2.trim(), "status": diagnostics.0, "journal": diagnostics.1, })) } } /// GET /api/cluster/proxmox-cleanup — return the notice (if any) of legacy /// Proxmox-API entries that were auto-removed on startup. The UI shows a /// banner while this exists. pub async fn proxmox_cleanup_notice(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::agent::ProxmoxCleanupNotice::load() { Some(notice) => HttpResponse::Ok().json(serde_json::json!({ "removed_count": notice.removed_count, "addresses": notice.addresses, "backup_path": notice.backup_path, "timestamp": notice.timestamp, })), None => HttpResponse::Ok().json(serde_json::json!({ "removed_count": 0 })), } } /// POST /api/cluster/proxmox-cleanup/dismiss — dismiss the banner (deletes notice file) pub async fn proxmox_cleanup_dismiss(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::agent::ProxmoxCleanupNotice::dismiss() { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "dismissed": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// GET /api/nodes — all cluster nodes pub async fn get_nodes(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let nodes = state.cluster.get_all_nodes(); // Per-user cluster filter. Cluster-node callers (inter-node // traffic via X-WolfStack-Secret) always see everything; the // helper returns "cluster-node" for those and find() below misses, // so the unfiltered path kicks in. Admin users also pass through // — the helper handles that. let filtered: Vec = filter_nodes_for_caller(&caller, nodes) .into_iter().map(crate::agent::Node::redacted_for_api).collect(); // Outage data for the "offline since" banner — only for nodes the caller // can see. let visible: std::collections::HashSet<&str> = filtered.iter().map(|n| n.id.as_str()).collect(); let mut open = crate::node_outages::open_outages(); open.retain(|id, _| visible.contains(id.as_str())); let mut last = crate::node_outages::last_closed_outages(); last.retain(|id, _| visible.contains(id.as_str())); HttpResponse::Ok().json(serde_json::json!({ "version": env!("CARGO_PKG_VERSION"), "nodes": filtered, "tls_enabled": state.tls_enabled, "outages": { "open": open, "last": last }, })) } /// GET /api/nodes/{id}/outages — this node's record of when that peer went /// offline and came back, newest first. pub async fn get_node_outages(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let id = path.into_inner(); let Some(node) = state.cluster.get_node(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })); }; if filter_nodes_for_caller(&caller, vec![node]).is_empty() { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "You don't have access to this cluster" })); } HttpResponse::Ok().json(serde_json::json!({ "outages": crate::node_outages::history_for(&id) })) } /// Filter a nodes list down to what the caller (by username) is /// allowed to see. The "cluster-node" pseudo-caller (inter-node /// auth) and any user not found in the store pass everything through /// — this is the safe default for service-to-service and for cases /// where a session exists without a matching user record. pub(crate) fn filter_nodes_for_caller(caller: &str, nodes: Vec) -> Vec { if caller == "cluster-node" { return nodes; } let store = crate::auth::users::UserStore::load(); let Some(user) = store.find(caller) else { return nodes; }; if user.role == "admin" || user.allowed_clusters.is_empty() { return nodes; } nodes.into_iter() .filter(|n| user.can_access_cluster(n.cluster_name.as_deref())) .collect() } /// GET /api/nodes/{id} — single node details pub async fn get_node(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let id = path.into_inner(); match state.cluster.get_node(&id) { Some(node) => { // Refuse if the caller can't see this cluster — same rule // as /api/nodes, applied to the single-node view. let store = crate::auth::users::UserStore::load(); if caller != "cluster-node" && let Some(user) = store.find(&caller) && !user.can_access_cluster(node.cluster_name.as_deref()) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "You don't have access to this cluster" })); } HttpResponse::Ok().json(node.redacted_for_api()) }, None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })), } } /// GET /api/auth/join-token — display this server's join token (session-auth required) pub async fn get_join_token(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp }; // The token + fingerprint were already readable by any authed caller // (pre-existing). The override + pending-one-time STATE is more sensitive // — it tells an attacker when a re-cluster window is open — so expose it // only to a local-admin session, never to cluster-node / api-key callers. let local_admin = caller != "cluster-node" && !caller.starts_with("apikey:"); let mut out = serde_json::json!({ "join_token": state.join_token, "cluster_fingerprint": crate::cluster_join::cluster_fingerprint(), }); if local_admin { out["pending_one_time"] = serde_json::json!(state.one_time_join_tokens.pending_count()); out["recluster_override_armed"] = serde_json::json!(crate::cluster_join::recluster_override_armed()); } HttpResponse::Ok().json(out) } /// POST /api/auth/join-token/rotate — regenerate the static per-install /// join token in /etc/wolfstack/join-token and return the NEW value once. /// Admin-gated. The in-memory `state.join_token` is process-immutable, so /// the new token takes effect for handshake verification after the next /// restart; until then BOTH old and new are written but only the /// in-memory (old) one verifies — we therefore tell the operator to /// restart. (Existing clusters keep polling on the cluster SECRET, not /// the join token, so this never disrupts steady-state traffic.) pub async fn rotate_join_token(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Local-admin only: a peer holding the cluster secret ("cluster-node") // or an API key must NOT be able to rotate another node's join token // remotely (it would disrupt legitimate joins to that node). if caller == "cluster-node" || caller.starts_with("apikey:") { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "The join token can only be rotated by a local admin session on this node.", })); } // Generate a fresh 64-hex token from the CSPRNG; refuse (don't mint a // weak token) if the CSPRNG is unavailable. let token = match crate::cluster_join::generate_token() { Ok(t) => t, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Could not generate join token: {}", e), })), }; if let Err(e) = crate::paths::write_secure("/etc/wolfstack/join-token", &token) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Could not write join token: {}", e), })); } cluster_join_audit(&state, &caller, "warning", "Join token rotated", "The static per-install join token was rotated", ""); HttpResponse::Ok().json(serde_json::json!({ "join_token": token, "note": "New static join token saved. Restart wolfstack on this node for \ it to take effect for verification; the previous token keeps \ working until restart.", })) } /// POST /api/auth/join-token/one-time — mint a single-use, ~15-minute /// join token. Admin-gated. Returned ONCE; consumed on first successful /// join. The static token still works alongside these. pub async fn mint_one_time_join_token(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Local-admin only — same reasoning as rotate_join_token. if caller == "cluster-node" || caller.starts_with("apikey:") { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "One-time join tokens can only be minted by a local admin session on this node.", })); } let token = match state.one_time_join_tokens.mint() { Ok(t) => t, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Could not generate one-time join token: {}", e), })), }; cluster_join_audit(&state, &caller, "info", "One-time join token minted", "A single-use 15-minute join token was generated", ""); HttpResponse::Ok().json(serde_json::json!({ "join_token": token, "expires_in_seconds": 900, "single_use": true, "note": "Single-use token, valid ~15 minutes. It is consumed on the first \ successful join.", })) } /// POST /api/cluster/recluster-override — arm the LOCAL re-cluster override /// on THIS node so it will accept a join into a DIFFERENT cluster (the /// otherwise hard-blocked silent re-cluster). Requires local admin auth on /// THIS node — a remote attacker with a stolen cluster secret can NOT arm /// it (require_auth accepts the cluster secret for inter-node calls, so we /// additionally reject the "cluster-node" actor here). Consumed on the /// next successful re-cluster. pub async fn arm_recluster_override(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Defence-in-depth: this override must be a LOCAL admin action. A // request authenticated only by the cluster secret (actor // "cluster-node") or an API key must not be able to arm it remotely. if caller == "cluster-node" || caller.starts_with("apikey:") { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "The re-cluster override can only be armed by a local admin \ session on this node, not via inter-node or API-key auth.", })); } if let Err(e) = crate::cluster_join::arm_recluster_override() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } cluster_join_audit(&state, &caller, "warning", "Re-cluster override armed", "Local override armed — this node will accept a join into a different cluster once", ""); HttpResponse::Ok().json(serde_json::json!({ "armed": true, "note": "This node will accept ONE join into a different cluster. The \ override is consumed on that join.", })) } /// DELETE /api/cluster/recluster-override — disarm the local re-cluster /// override. Local-admin gated (same as arming). pub async fn clear_recluster_override(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; if caller == "cluster-node" || caller.starts_with("apikey:") { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "The re-cluster override can only be changed by a local admin \ session on this node.", })); } let was_armed = crate::cluster_join::recluster_override_armed(); crate::cluster_join::clear_recluster_override(); if was_armed { cluster_join_audit(&state, &caller, "info", "Re-cluster override disarmed", "Local re-cluster override was manually disarmed", ""); } HttpResponse::Ok().json(serde_json::json!({ "armed": false })) } /// GET /api/cluster/verify-token?token=xxx — verify a join token. /// /// SECURITY (cluster-join hardening): the interactive admin "Add node" /// flow no longer uses this token-only GET path — it goes through the /// authenticated POST `/api/cluster/join-handshake` which additionally /// requires the TARGET node's admin username+password. A leaked join /// token (or cluster secret) alone must not let anyone graft a server /// onto a fleet. /// /// This GET endpoint therefore now REFUSES token-only verification UNLESS /// the caller is the secret-gated automated pool-bootstrap flow, which /// signals itself with `&bootstrap=1` (see `cluster_bootstrap_add`, which /// is independently gated on the cluster's *custom* secret). The practical /// effect is the intended security upgrade: an OLD master (one running /// pre-hardening code that calls this GET path with no admin creds and no /// bootstrap marker) adding a NEW node will be REJECTED by this new /// target — exactly what we want; the operator must upgrade the master so /// the admin-credentialled handshake is used. pub async fn verify_join_token(state: web::Data, query: web::Query>) -> HttpResponse { let provided = query.get("token").map(|s| s.as_str()).unwrap_or(""); if provided.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing token parameter" })); } // Only the automated, custom-secret-gated pool-bootstrap flow may use // the token-only path. Everything else must use the admin handshake. let bootstrap = query.get("bootstrap").map(|s| s == "1").unwrap_or(false); if !bootstrap { return HttpResponse::Forbidden().json(serde_json::json!({ "valid": false, "error": "This node requires the authenticated join handshake \ (admin username + password). Upgrade the cluster master \ so it sends admin credentials when adding a node.", "requires_handshake": true, })); } // Accept either the static per-install token (backward compat) or a // valid unexpired one-time token (consumed on success). let token_ok = crate::auth::validate_cluster_secret(provided, &state.join_token) || state.one_time_join_tokens.verify_and_consume(provided); if token_ok { HttpResponse::Ok().json(serde_json::json!({ "valid": true, "hostname": hostname::get().map(|h| h.to_string_lossy().to_string()).unwrap_or_default(), "cluster_fingerprint": crate::cluster_join::cluster_fingerprint(), })) } else { HttpResponse::Forbidden().json(serde_json::json!({ "valid": false, "error": "Invalid join token", })) } } /// Decide whether an incoming join is a SILENT RE-CLUSTER that must be /// hard-blocked (absent a local override). True when this node is already /// an active member of a cluster (`has_peers`) AND the master is NOT /// adding us back into our own cluster — i.e. the declared `incoming` /// cluster name either differs from `our_cluster` OR is empty/omitted. /// /// The empty-name case is deliberately treated as a re-cluster for a node /// that already has peers: an already-joined node should only accept a /// re-add that explicitly names the cluster it's already in. This closes /// the bypass where a caller with a valid token + admin creds could skip /// the hard-block simply by omitting `cluster_name`. A fresh single-node /// install (`!has_peers`) is never a re-cluster regardless of the name, so /// first-time joins (which may legitimately omit the name) are unaffected. /// Pure function so the decision is unit-tested independently of HTTP /// state. fn is_silent_recluster(has_peers: bool, our_cluster: &str, incoming: &str) -> bool { has_peers && incoming != our_cluster } /// Request body for the hardened POST join handshake. The master sends the /// join token PLUS the TARGET node's admin credentials, which the target /// verifies against its own auth before accepting the join. Credentials /// are forwarded over the existing TLS inter-node channel and are NEVER /// logged or persisted. #[derive(Deserialize)] pub struct JoinHandshakeRequest { pub token: String, /// TARGET node's admin username (verified by the target). #[serde(default)] pub admin_username: String, /// TARGET node's admin password (verified by the target; never logged). #[serde(default)] pub admin_password: String, /// The cluster name the master is adding this node into — used to /// decide whether this is a silent re-cluster (hard-blocked) vs a /// no-op join into the cluster the node already belongs to. #[serde(default)] pub cluster_name: Option, /// The MASTER's own API port + self_id, so the joining node can seed the /// master into its OWN registry (keyed by the master's source IP = its LAN /// address as the joiner sees it). Without this the joiner only knows /// itself, never polls the master, and the membership permanently splits — /// the master sees everyone, the added nodes only see each other (wabil /// 2026-06-27). Optional for backward-compat with older masters. #[serde(default)] pub master_port: Option, #[serde(default)] pub master_self_id: Option, } /// POST /api/cluster/join-handshake — the hardened, admin-credentialled /// join handshake (cluster-join security hardening). /// /// Called by the master's `add_node` on the TARGET node to initiate /// membership. Self-authenticating (no `require_auth`): it validates the /// join token AND the target's admin credentials itself. Enforces, in /// order: /// 1. Valid join token (static per-install OR one-time short-TTL). /// 2. TARGET admin username+password (`verify_target_admin`) — proves /// the operator controls the server being added; a leaked secret or /// token alone is insufficient. /// 3. Hard-block silent re-clustering: if this node is ALREADY a member /// of a different cluster, refuse unless the local re-cluster /// override is armed (a local-admin action on the target). Consumes /// the override on success. /// /// On success it audits the join, raises a security ALERT, and returns the /// cluster fingerprint for mutual verification. pub async fn cluster_join_handshake( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // Source IP of the joining master — recorded in the audit log so a // join from an unexpected host is forensically visible. Canonicalised // (a dual-stack listener reports v4 peers as ::ffff:a.b.c.d). let peer_ip = req.peer_addr() .map(|a| a.ip().to_canonical().to_string()) .unwrap_or_default(); let provided = body.token.trim(); if provided.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "valid": false, "error": "Missing join token", })); } // Brute-force guard: reuse the same per-IP lockout the interactive login // uses. An attacker holding the cluster secret + join token must not be // able to hammer this endpoint to brute-force an admin password. if state.login_limiter.is_locked_out(&peer_ip) { state.login_limiter.audit_blocked(&peer_ip, "cluster-join"); return HttpResponse::TooManyRequests().json(serde_json::json!({ "valid": false, "error": "Too many failed attempts — temporarily locked out.", })); } // 1) Join token: static per-install OR one-time. For a one-time token we // TAKE it atomically NOW (concurrency-safe single-use — two racing // requests can't both succeed). If a LATER step fails we reinsert it // (`ott_expiry`) so a failed admin attempt doesn't burn the operator's // token. A matching static token never touches the one-time pool. let static_ok = crate::auth::validate_cluster_secret(provided, &state.join_token); let ott_expiry = if static_ok { None } else { state.one_time_join_tokens.take(provided) }; if !static_ok && ott_expiry.is_none() { return HttpResponse::Forbidden().json(serde_json::json!({ "valid": false, "error": "Invalid join token", })); } // 2) Admin credential proof against THIS node's own auth. Run the // crypt()/role check inside web::block — it reads /etc/shadow and // /etc/group and must not park an actix worker. The password is // moved in and dropped inside the closure; never logged. let admin_user = body.admin_username.trim().to_string(); let admin_pass = body.admin_password.clone(); if admin_user.is_empty() || admin_pass.is_empty() { if let Some(exp) = ott_expiry { state.one_time_join_tokens.reinsert(provided, exp); } return HttpResponse::Unauthorized().json(serde_json::json!({ "valid": false, "error": "Admin username and password for THIS node are required to add it to a cluster.", })); } let admin_ok = { let u = admin_user.clone(); match web::block(move || crate::auth::verify_target_admin(&u, &admin_pass)).await { Ok(v) => v, Err(_) => { // Blocking pool exhausted — fail-closed but don't tell the // operator the password was wrong; signal "busy, retry". if let Some(exp) = ott_expiry { state.one_time_join_tokens.reinsert(provided, exp); } return HttpResponse::ServiceUnavailable().json(serde_json::json!({ "valid": false, "error": "Server busy — try again in a moment.", })); } } }; if !admin_ok { // Count toward the per-IP lockout AND leave an audit trail so a // brute-force attempt against this endpoint is visible. state.login_limiter.record_failure_with(&peer_ip, &admin_user); cluster_join_audit( &state, &admin_user, "warning", "Cluster join admin auth FAILED", &format!("Rejected admin credentials for a join handshake from {}", if peer_ip.is_empty() { "unknown source" } else { &peer_ip }), &peer_ip, ); if let Some(exp) = ott_expiry { state.one_time_join_tokens.reinsert(provided, exp); } return HttpResponse::Unauthorized().json(serde_json::json!({ "valid": false, "error": "Admin credentials rejected — the supplied username/password \ must be an admin account on the node being added.", })); } // 3) Hard-block silent re-clustering. "Already a member of a different // cluster" = this node has peers OTHER than itself AND the cluster // name the master is adding us into differs from our own. A node // re-joining the cluster it's already in (same name), or a fresh // single-node install, is unaffected. let our_cluster = state.cluster.get_self_cluster_name(); let has_peers = !has_no_other_peers(&state); let incoming = body.cluster_name.clone().unwrap_or_default(); if is_silent_recluster(has_peers, &our_cluster, &incoming) { if crate::cluster_join::recluster_override_armed() { // Operator explicitly armed the override locally — allow, and // consume it so it can't linger as a standing hole. crate::cluster_join::clear_recluster_override(); } else { if let Some(exp) = ott_expiry { state.one_time_join_tokens.reinsert(provided, exp); } return HttpResponse::Conflict().json(serde_json::json!({ "valid": false, "error": format!( "This node is already a member of cluster '{}' — remove it from \ that cluster first, or arm the local re-cluster override on this \ node (Settings → Cluster → Allow re-cluster) before joining '{}'.", our_cluster, incoming ), "already_in_cluster": our_cluster, "override_required": true, })); } } // 4) Protect the PROVEN manager from auto-bans before anything else in // the join flow can trip a detector: token + this node's admin creds // are both verified above, so the source is operator-controlled by // definition. Sticky (30 days, persisted) so the protection survives // this node falling back out of the cluster mid-join — the exact // window where stale-secret polling used to get the manager banned // and the re-add could never connect (klasSponsor 2026-07-16). Also // clear accumulated app-level failures (mistyped passwords during // this very add) — same as interactive login success — and heal any // leftover kernel ban. iptables is a sync subprocess → web::block. if !peer_ip.is_empty() { state.login_limiter.clear_with(&peer_ip, &admin_user); let pip = peer_ip.clone(); if let Err(e) = web::block(move || { crate::auth::record_known_peer_ip(&pip); crate::auth::kernel_unblock_ip(&pip); }).await { // Best-effort side channel — the join itself proceeds, but the // operator should be able to see the protection didn't land. tracing::warn!( "cluster-join: could not persist ban protection for manager {}: {}", peer_ip, e ); } } // 5) Audit + security alert — make a join loud. `admin_user` is // guaranteed non-empty here (rejected above), so it is the actor. let actor = admin_user.clone(); let target_cluster = if incoming.is_empty() { our_cluster.clone() } else { incoming.clone() }; cluster_join_audit( &state, &actor, "warning", "Node joined cluster", &format!( "Authenticated join accepted (admin '{}', into cluster '{}', from {})", actor, target_cluster, if peer_ip.is_empty() { "unknown source" } else { &peer_ip } ), &peer_ip, ); let alert_title = "Cluster join accepted"; let alert_body = format!( "A node-join handshake was accepted on this host.\n\ Admin verified: {}\n\ Source IP: {}\n\ Target cluster: {}\n\ If you did not initiate this, treat it as a possible hijack.", actor, if peer_ip.is_empty() { "unknown".into() } else { peer_ip.clone() }, target_cluster, ); crate::alerting::send_local_alert( crate::alerting::AlertCategory::Posture, alert_title, &alert_body, ).await; // The one-time token (if used) was already consumed atomically at step 1 // via `take`, and was reinserted on every failure path above — so a // success here means it is correctly single-use with no consume race. // Mint a single-use bootstrap grant. The master presents it on the // immediately-following /api/cluster/secret/receive push so the fleet // secret can be adopted even though we currently hold a DIFFERENT secret // (otherwise that push fails inter-node auth and we stay divergent — our // resources then never appear to the cluster). Best-effort: if minting // fails (CSPRNG), the master falls back to the legacy secret/default auth. let bootstrap_grant = state.bootstrap_grants.mint().ok(); // Seed the MASTER into THIS node's registry, keyed by its source IP — the // master's LAN address as we (the joiner) see it. This is the only thing // that makes membership converge: without it the added node knows only // itself, never polls the master, and the cluster splits (the master sees // everyone; the added nodes see only each other — wabil 2026-06-27). // Using peer_ip also sidesteps the master self-identifying by a reverse- // proxy/WAN hostname: we learn it by the dialable LAN IP, which the gossip // is_private guard then accepts (and a WAN-hostname duplicate is skipped). // Marked join_verified (the master proved the join token + this node's // admin creds). self_id is learned on the first poll; address+port dedup // prevents a duplicate in the meantime. if !peer_ip.is_empty() && peer_ip.parse::().map(|ip| !ip.is_loopback()).unwrap_or(false) { let master_port = body.master_port.unwrap_or(8553); let already = state.cluster.get_all_nodes().into_iter().any(|n| { (body.master_self_id.as_deref().filter(|s| !s.is_empty()).is_some() && n.self_id.as_deref() == body.master_self_id.as_deref()) || (n.address == peer_ip && n.port == master_port) }); if !already { let id = state.cluster.add_server( peer_ip.clone(), master_port, body.cluster_name.clone(), ); tracing::info!(target: "cluster-join", "Seeded master {}:{} into local registry as {} on join", peer_ip, master_port, id); } } let mut resp_body = serde_json::json!({ "valid": true, "hostname": hostname::get().map(|h| h.to_string_lossy().to_string()).unwrap_or_default(), "cluster_fingerprint": crate::cluster_join::cluster_fingerprint(), "cluster_name": our_cluster, }); // Only include the grant when minting succeeded — never emit a null field // (which would needlessly reveal a CSPRNG failure). if let Some(g) = bootstrap_grant { resp_body["bootstrap_grant"] = serde_json::json!(g); } HttpResponse::Ok().json(resp_body) } /// Append a cluster-join / secret-change entry to BOTH the persistent /// audit log (`compat::audit_log`, the same store the API-key audit uses) /// AND the in-memory alert_log surfaced in the Tasks panel. Security- /// relevant events (join, secret change) must be investigable later. fn cluster_join_audit( state: &web::Data, actor: &str, severity: &str, title: &str, detail: &str, // Source IP of the request, where one is meaningful (e.g. the join // handshake's peer address). Empty for locally-initiated events // (session-authed secret rotation, master-side add). Recorded in the // persistent audit log so a join from an unexpected host is visible. ip: &str, ) { // Persistent audit log — reuse the AuditEntry shape. We encode the // event into the human-readable fields; status 200 = accepted. crate::compat::audit_log(&crate::compat::AuditEntry { timestamp: chrono::Utc::now().to_rfc3339(), key_name: format!("{title} ({actor})"), key_id: "cluster-join".to_string(), method: "JOIN".to_string(), path: detail.to_string(), ip: ip.to_string(), status: 200, }); // In-memory alert log for the Tasks panel. let now = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(); let hostname = state.cluster.get_all_nodes().into_iter() .find(|n| n.is_self).map(|n| n.hostname).unwrap_or_default(); let cluster = state.cluster.get_self_cluster_name(); let mut log = state.alert_log.write().unwrap_or_else(|e| e.into_inner()); let id = log.last().map(|e| e.id + 1).unwrap_or(1); log.push(AlertLogEntry { id, timestamp: now, severity: severity.into(), title: title.into(), detail: format!("{} (by {})", detail, actor), hostname, cluster, }); while log.len() > 200 { log.remove(0); } } // ─── Cluster Secret Management ─── /// GET /api/cluster/secret-status — check whether a custom cluster secret is active pub async fn cluster_secret_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Check the on-disk secret (not just in-memory) so status is correct even before restart let active = crate::auth::load_cluster_secret(); let has_custom = active != crate::auth::default_cluster_secret(); HttpResponse::Ok().json(serde_json::json!({ "has_custom_secret": has_custom, "node_identity": crate::node_identity::status(), })) } #[derive(Deserialize)] pub struct NodeSignaturesBody { pub required: bool, } /// POST /api/cluster/node-signatures — operator opt-in to Strict mode /// (`{"required": true}`), or back to Transition. Refused while any peer /// has no pinned key, so it can never cut a node off. pub async fn cluster_node_signatures_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match require_operator_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; match crate::node_identity::set_mode(body.required) { Ok(()) => { tracing::warn!("node identity: '{}' set require-signatures = {}", caller, body.required); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "node_identity": crate::node_identity::status(), })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/nodes/{id}/reset-identity — forget a peer's pinned key so the /// next status report from it is pinned afresh (a reinstalled node). /// Operator-only. Local to this node's view; run it where the mismatch /// warning appears, or on every node for a fleet-wide reset. pub async fn node_reset_identity( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let caller = match require_operator_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let id = path.into_inner(); let found = { let mut nodes = state.cluster.nodes_write(); match nodes.get_mut(&id) { Some(n) if !n.is_self => { n.pubkey = None; true } _ => false, } }; if !found { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found (or is this node)" })); } state.cluster.save_nodes(); tracing::warn!("node identity: '{}' reset the pinned key for node {}", caller, id); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } #[derive(Deserialize)] pub struct NodePolicyBody { pub node_id: String, pub manager: bool, } /// POST /api/cluster/node-policy — a peer forwards an operator's change to /// a node's `manager` flag so every node applies the same policy. Operator /// gate: session/API key, or a manager peer forwarding one. pub async fn cluster_node_policy_receive( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let changed = { let mut nodes = state.cluster.nodes_write(); let mut hit = false; for n in nodes.values_mut() { if n.id == body.node_id || n.self_id.as_deref() == Some(body.node_id.as_str()) { n.manager = body.manager; hit = true; } } hit }; if changed { state.cluster.save_nodes(); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "applied": changed })) } /// POST /api/cluster/secret/generate — generate a new cluster secret and propagate to all nodes pub async fn cluster_secret_generate(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // ORDERING: capture the OLD on-disk secret BEFORE writing the new one // (the secret IS the at-rest encryption key). Then persist the new // secret, then re-key all at-rest stores from old→new so they remain // decryptable after the restart that follows rotation. let old_secret = crate::auth::load_cluster_secret(); let new_secret = crate::auth::generate_cluster_secret(); if let Err(e) = crate::auth::save_cluster_secret(&new_secret) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Re-encrypt local at-rest secrets (no-op if old == new). Runs inside // web::block — it's a sequence of std::fs reads/writes on // /etc/wolfstack/ that must not park an actix worker on disk I/O. let reencrypt = web::block({ let old = old_secret.clone(); let new = new_secret.clone(); move || crate::secret_rotation::reencrypt_all_at_rest(&old, &new) }).await.ok(); // Propagate to all online nodes across all clusters let nodes = state.cluster.get_all_nodes(); let client = &*API_HTTP_CLIENT; let mut results = Vec::new(); for node in &nodes { if node.is_self || !node.online || node.node_type == "proxmox" { continue; } let urls = build_node_urls(&node.address, node.port, "/api/cluster/secret/receive"); let mut pushed = false; let mut err = String::new(); for url in &urls { // Stage 5 fix: pre-fix this used `default_cluster_secret()` which // only worked on never-rotated installs. Use the current in-memory // secret — peers accept any of {in-memory, on-disk, default} via // validate_inter_node_secret, so this works regardless of whether // the cluster has rotated before. match client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(state.cluster_secret.clone()) .json(&serde_json::json!({ "secret": new_secret })) .send() .await { Ok(resp) if resp.status().is_success() => { pushed = true; let _ = resp.bytes().await; break; } Ok(resp) => { err = format!("HTTP {}", resp.status()); let _ = resp.bytes().await; } Err(e) => { err = format!("{}", e); } } } results.push(serde_json::json!({ "node": if node.hostname.is_empty() { &node.address } else { &node.hostname }, "address": node.address, "success": pushed, "error": if pushed { "" } else { &err }, })); } // Audit + alert the secret change — a cluster-secret rotation is a // security-relevant event that must be loud and investigable. cluster_join_audit( &state, &caller, "warning", "Cluster secret changed", "Cluster secret rotated (generate) and propagated to peers", "", ); crate::alerting::send_local_alert( crate::alerting::AlertCategory::Posture, "Cluster secret changed", &format!("The cluster secret was rotated by {}. If this was not you, \ treat it as a possible compromise.", caller), ).await; HttpResponse::Ok().json(serde_json::json!({ "generated": true, "nodes": results, "at_rest_reencrypt": reencrypt, })) } /// POST /api/cluster/secret/repush — re-push the existing custom secret to all nodes pub async fn cluster_secret_repush(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let active = crate::auth::load_cluster_secret(); if active == crate::auth::default_cluster_secret() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "No custom secret to push — generate one first" })); } let nodes = state.cluster.get_all_nodes(); let client = &*API_HTTP_CLIENT; let mut results = Vec::new(); for node in &nodes { if node.is_self || !node.online || node.node_type == "proxmox" { continue; } let urls = build_node_urls(&node.address, node.port, "/api/cluster/secret/receive"); let mut pushed = false; let mut err = String::new(); for url in &urls { // Stage 5 fix: same as cluster_secret_generate above. match client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(state.cluster_secret.clone()) .json(&serde_json::json!({ "secret": active })) .send() .await { Ok(resp) if resp.status().is_success() => { pushed = true; let _ = resp.bytes().await; break; } Ok(resp) => { err = format!("HTTP {}", resp.status()); let _ = resp.bytes().await; } Err(e) => { err = format!("{}", e); } } } results.push(serde_json::json!({ "node": if node.hostname.is_empty() { &node.address } else { &node.hostname }, "address": node.address, "success": pushed, "error": if pushed { "" } else { &err }, })); } HttpResponse::Ok().json(serde_json::json!({ "pushed": true, "nodes": results, })) } // ─── Cluster Leave ──────────────────────────────────────────────────── // // Used when a node ends up stranded in the wrong cluster — typically // because the cluster was renamed on another node while this one was // offline, and now every cross-cluster operation (route create, status // page, etc.) is rejected by the strict-cluster guard // (`networking::router::api` ~line 5690). The flow: // // 1. Best-effort broadcast `DELETE /api/nodes/{self_id}` to every // online peer so they tombstone us instead of gossiping us back. // 2. Drop in-memory peer + tombstone state so any save fired during // the shutdown gap writes empty. // 3. Unlink `self_cluster.json`, `nodes.json`, `deleted_nodes.json`, // and `node_id` (see `agent::leave_wipe_membership_files`). // 4. Optionally rotate the cluster secret. // 5. Schedule `systemctl restart wolfstack` so the daemon comes back // up with fresh state and a new `node_id`. #[derive(Deserialize, Default)] pub struct ClusterLeaveRequest { /// When true, also generate a new `custom-cluster-secret`. Old peers /// can then no longer authenticate inter-node calls to this server /// even if they retain a stale entry for it. #[serde(default)] pub rotate_secret: bool, } #[derive(Serialize)] pub struct ClusterLeavePeerResult { pub node_id: String, pub hostname: String, pub address: String, pub success: bool, pub error: String, } /// POST /api/cluster/leave — drop this node out of its cluster and /// restart so it comes back up as a fresh single-node cluster. pub async fn cluster_leave( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Snapshot what we need before we start wiping state. self_id is the // ID our peers know us by; the broadcast carries it as the path // parameter so each peer can `remove_server` the right entry. let self_id = state.cluster.self_id.clone(); let secret = state.cluster_secret.clone(); let previous_cluster_name = state.cluster.get_node(&self_id) .and_then(|n| n.cluster_name.clone()); let peers: Vec<_> = state.cluster.get_all_nodes() .into_iter() .filter(|n| !n.is_self && n.online && n.node_type == "wolfstack") .collect(); // Step 1: best-effort broadcast. Each peer gets the same 3-URL // fallback ladder as the existing `remove_node` broadcast at // api/mod.rs ~line 2503, so behaviour matches what they'd expect // from a manual DELETE. let client = &*API_HTTP_CLIENT; let mut peer_results: Vec = Vec::with_capacity(peers.len()); for peer in &peers { let urls = build_node_urls(&peer.address, peer.port, &format!("/api/nodes/{}", self_id)); let mut success = false; let mut err = String::new(); for url in &urls { match client.delete(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .send() .await { Ok(resp) if resp.status().is_success() => { success = true; let _ = resp.bytes().await; break; } Ok(resp) => { err = format!("HTTP {}", resp.status()); let _ = resp.bytes().await; } Err(e) => { err = e.to_string(); } } } peer_results.push(ClusterLeavePeerResult { node_id: peer.id.clone(), hostname: if peer.hostname.is_empty() { peer.address.clone() } else { peer.hostname.clone() }, address: peer.address.clone(), success, error: if success { String::new() } else { err }, }); } // Step 2: drop in-memory peer state so any background `save_nodes()` // in the next 1.5s writes an empty list rather than re-creating the // file we're about to delete. state.cluster.clear_membership_in_memory(); // Step 3: wipe the on-disk membership files. let wipe = crate::agent::leave_wipe_membership_files(); // Step 4: optional secret rotation. Done last so the broadcast // above (which used the *current* secret) can't be rejected. let mut secret_rotated = false; let mut secret_error: Option = None; if body.rotate_secret { // ORDERING: capture OLD on-disk secret before save so the node's // own at-rest stores (it keeps running standalone after leaving) // can be re-keyed old→new. Without this, leaving + rotating would // orphan every local SQL / OIDC / integration / DNS / cloud / XO // credential after the restart below. let old_secret = crate::auth::load_cluster_secret(); let new_secret = crate::auth::generate_cluster_secret(); match crate::auth::save_cluster_secret(&new_secret) { Ok(()) => { secret_rotated = true; let report = web::block(move || { crate::secret_rotation::reencrypt_all_at_rest(&old_secret, &new_secret) }).await; if let Ok(r) = report && !r.errors.is_empty() { tracing::warn!(target: "secret_rotation", "cluster-leave rotation: {} store(s) failed re-encrypt: {}", r.errors.len(), r.errors.join("; ")); } } Err(e) => secret_error = Some(e), } } // Step 5: schedule the restart. Use the same detached-thread + // ~1.5s delay pattern as `installer::restart_cert_service` so the // HTTP response below flushes back to the caller before systemd // kills us. `Restart=on-failure` in the unit means we have to call // `systemctl restart` explicitly — a plain `exit(0)` would NOT // respawn us. let restart_in_ms: u64 = 1500; std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(restart_in_ms)); let _ = std::process::Command::new("systemctl") .args(["restart", "wolfstack"]) .output(); }); HttpResponse::Ok().json(serde_json::json!({ "left": true, "previous_cluster_name": previous_cluster_name.or(wipe.previous_cluster_name), "peer_results": peer_results, "files": wipe.files, "secret_rotated": secret_rotated, "secret_error": secret_error, "restart_in_ms": restart_in_ms, })) } /// Has this process already scheduled an auto-restart in response to /// a fresh-bootstrap secret push? Idempotency guard so multiple rapid /// pushes don't queue redundant restarts. static BOOTSTRAP_RESTART_SCHEDULED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// True if this node has no peers OTHER THAN ITSELF — the "I'm a /// fresh install that's just being bootstrapped into a cluster" /// signal as observed by the receiving endpoint. Defence-in-depth /// for the auto-restart logic: even if a buggy caller sends the /// bootstrap flag against an active cluster member, this check /// blocks the restart. /// /// Note: we look at AppState.cluster.nodes (in-memory, post-startup) /// rather than nodes.json on disk — by the time a push arrives, /// ClusterState::new has already written the self entry to disk, so /// the on-disk file always has at least one entry. The in-memory /// map's self-exclusion is the right "do I have any OTHER peers" /// signal. fn has_no_other_peers(state: &AppState) -> bool { // nodes_read recovers from poisoning, so there is no longer a // "lock is unusable" arm to fall back on — we always get to answer // from real membership rather than guessing "not fresh". let nodes = state.cluster.nodes_read(); let self_id = state.cluster.self_id.as_str(); !nodes.values().any(|n| n.id != self_id) } /// POST /api/cluster/secret/receive — receive a new cluster secret /// from the cluster's admin node. Two trigger paths: /// 1. add_node bootstrap push — receiving node is a fresh install /// being joined to an existing cluster. Auto-restart after save /// so the operator doesn't have to manually align state. /// 2. legacy fleet-rotate push — receiving node is an active /// cluster member. NEVER auto-restart; rotation docs explicitly /// say "restart when convenient" so existing work isn't /// interrupted. /// We distinguish by checking whether this node has any peers /// configured: a peerless node is fresh (case 1); a node with peers /// is active (case 2). pub async fn cluster_secret_receive(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Auth: the normal inter-node secret, OR a single-use bootstrap grant this // node minted in its own join-handshake moments ago. The grant path lets a // node that currently holds a DIFFERENT secret adopt the fleet secret right // after an admin-authenticated join (without it, this push fails inter-node // auth, the node stays divergent, and its resources never appear to the // cluster). The grant is checked ONLY when the normal auth fails — so an // existing valid push is byte-identical and never consumes a grant — and it // is single-use (consumed here). let mut authed_via_grant = false; match require_cluster_auth(&req, &state) { Ok(_) => {} Err(resp) => { let grant_ok = body.get("bootstrap_grant") .and_then(|v| v.as_str()) // Real grants are 64 hex chars; cap the input so an attacker // can't feed enormous strings into the constant-time scan. .filter(|g| g.len() <= 128) .map(|g| state.bootstrap_grants.take(g).is_some()) .unwrap_or(false); if !grant_ok { return resp; } authed_via_grant = true; } } if authed_via_grant { // A secret adopted via the grant path = a freshly-joined node taking // the fleet secret. Audit it (with source IP) so grant-path use is // visible in the trail, distinct from a normal cluster-auth push. let peer = req.peer_addr() .map(|a| a.ip().to_canonical().to_string()) .unwrap_or_default(); cluster_join_audit( &state, "cluster-node", "warning", "Cluster secret adopted via bootstrap grant", &format!("New cluster secret accepted via a single-use bootstrap grant from {}", if peer.is_empty() { "unknown source" } else { &peer }), &peer, ); } let secret = match body.get("secret").and_then(|v| v.as_str()) { Some(s) if !s.is_empty() => s, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing secret" })), }; // Idempotency: if the pushed value matches what we already have // in memory, the save is a no-op AND we don't need a restart. let secret_actually_changed = secret != state.cluster_secret.as_str(); // Explicit bootstrap signal from the caller. `add_node` sets this // when pushing to a freshly-joined node so the receiver knows // it's safe to self-restart. Old-code masters won't include this // field; serde_json::Value parsing ignores its absence and the // restart path stays inactive — receiver falls back to "manual // restart required" semantics, preserving the legacy behaviour. let bootstrap_intent = body.get("bootstrap").and_then(|v| v.as_bool()).unwrap_or(false); // ORDERING: capture the OLD on-disk secret BEFORE the save so we can // re-key this node's own at-rest stores from old→new. (The secret is // the at-rest encryption key; a received-but-not-re-keyed node would // have undecryptable local credentials after its restart.) let old_secret = crate::auth::load_cluster_secret(); if let Err(e) = crate::auth::save_cluster_secret(secret) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Re-key local at-rest secrets only when the value actually changed. // Re-key when the ON-DISK old secret differs from the pushed value. We // compare against `old_secret` (on disk), NOT the in-memory // `secret_actually_changed`: a node that committed a new secret but hasn't // restarted has disk != memory, and gating on the stale in-memory value // could skip the re-key and silently orphan local data. (A fresh-bootstrap // node typically has no stored credentials, so this is a cheap no-op; and // reencrypt_all_at_rest also no-ops internally when old == new.) let reencrypt = if secret != old_secret.as_str() { let old = old_secret.clone(); let new = secret.to_string(); web::block(move || crate::secret_rotation::reencrypt_all_at_rest(&old, &new)) .await.ok() } else { None }; // Auto-restart only when ALL four guards pass: // • caller explicitly tagged this as a bootstrap (`bootstrap: true`) // • the secret actually changed (avoid pointless restarts on // idempotent pushes) // • we have no peers OTHER than ourselves (defence-in-depth: even // if a buggy caller sends bootstrap=true against an active // cluster member, this catches it) // • we haven't already scheduled a restart in this process (the // AtomicBool deduplicates rapid successive pushes) let mut restart_scheduled = false; if bootstrap_intent && secret_actually_changed && has_no_other_peers(&state) && BOOTSTRAP_RESTART_SCHEDULED .compare_exchange(false, true, std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst).is_ok() { restart_scheduled = true; // 3-second delay so the HTTP response flushes and the // calling node sees the success ACK before our service // begins shutdown. systemctl --no-block returns immediately // (queues the restart with systemd); the actual SIGTERM // arrives milliseconds later but we've already returned. tokio::spawn(async { tokio::time::sleep(std::time::Duration::from_secs(3)).await; tracing::info!(target: "cluster_secret", "bootstrap secret-push received on fresh install — \ self-restarting to load new secret into memory"); let _ = tokio::task::spawn_blocking(|| { std::process::Command::new("systemctl") .args(["restart", "--no-block", "wolfstack.service"]) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() }).await; }); } // Audit + alert when the secret actually changed (skip idempotent // re-pushes so steady-state propagation doesn't spam the log). The // caller is an inter-node push, so the actor is the cluster. if secret_actually_changed { let push_ip = req.peer_addr() .map(|a| a.ip().to_canonical().to_string()) .unwrap_or_default(); cluster_join_audit( &state, "cluster-node", "warning", "Cluster secret changed", "Received a new cluster secret from the cluster admin node", &push_ip, ); crate::alerting::send_local_alert( crate::alerting::AlertCategory::Posture, "Cluster secret changed", "This node received and stored a new cluster secret pushed by the \ cluster admin node. If this was unexpected, investigate.", ).await; } HttpResponse::Ok().json(serde_json::json!({ "saved": true, "auto_restart_scheduled": restart_scheduled, "at_rest_reencrypt": reencrypt, "note": if restart_scheduled { "Bootstrap secret saved. Self-restart scheduled in 3 seconds to \ load the new secret into memory. The cluster will be fully \ aligned with this node once it comes back up (typically 3-8s)." } else if !secret_actually_changed { "Secret unchanged — no restart needed." } else { "Secret saved. Restart wolfstack to load it into memory; until \ restart, both old and new secret are accepted (auth checks \ read disk as a fallback)." } })) } /// POST /api/nodes — add a server to the cluster #[derive(Deserialize)] #[allow(dead_code)] pub struct AddServerRequest { pub address: String, pub port: Option, #[serde(default)] pub node_type: Option, // "wolfstack" (default) or "proxmox" (rejected with 410) #[serde(default)] pub join_token: Option, // Required for WolfStack nodes — validates against remote // Cluster-join hardening: the TARGET node's admin username + password. // The target verifies these against its OWN auth before accepting the // join, so a leaked join token / cluster secret alone can't graft a // server onto a fleet. Forwarded over the existing TLS inter-node // channel; NEVER logged or persisted on the master. #[serde(default)] pub target_admin_username: Option, #[serde(default)] pub target_admin_password: Option, // Legacy Proxmox-only fields: kept on the struct so old clients still get parsed // (and answered with a friendly 410) instead of a JSON deserialisation error. #[serde(default)] pub pve_token: Option, #[serde(default)] pub pve_fingerprint: Option, #[serde(default)] pub pve_node_name: Option, #[serde(default)] pub pve_cluster_name: Option, #[serde(default)] pub cluster_name: Option, // Generic cluster name for WolfStack nodes } pub async fn add_node(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Capture the operator identity up front — it gates the whole handler // AND labels the post-add audit entry (no second require_auth call). let add_actor = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; // Adding a node is a LOCAL-ADMIN action only. Reject cluster-node and // api-key callers: otherwise a holder of the cluster secret could make // this master relay an operator-supplied admin password to any reachable // target's join-handshake, turning the master into a brute-force oracle. if add_actor == "cluster-node" || add_actor.starts_with("apikey:") { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Adding a node requires an interactive admin session." })); } // SSRF prevention: block loopback and link-local addresses if is_ssrf_blocked_address(&body.address) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Node address is not allowed (loopback/link-local)" })); } // Licence host-cap policy: SOFT cap, never hard block. // // Going over your tier's host count gets you a warning attached to // the response (and a banner in the dashboard) but the join still // succeeds. Reconciliation happens server-side via the daily licence // heartbeat. We never block someone from using WolfStack because // they outgrew their tier — that's a sales conversation, not an // outage. let cap_warning: Option = if let Some(dm) = crate::compat::license_manifest() { let tier = crate::compat::resolve_tier(&dm); let cap = crate::compat::effective_cap(tier, dm.max_nodes); if cap > 0 { let current = state.cluster.get_all_nodes().len() as u32; if current + 1 > cap { // Tier names/prices/caps per web/includes/stripe-tiers.php // (homelab £12/10, homelab_plus £29/25, team £149/150, msp // £499/unlimited). Suggest the NEXT rung of the ladder. // // Key the suggestion off the RAW tier slug, not resolve_tier: // resolve_tier collapses `homelab_plus` → `homelab` (same // feature bundle), so it can't tell the two apart — but their // upgrade paths differ (Homelab → Homelab Plus, Homelab Plus → // Team). Fall back to resolve_tier's name for tier-less legacy // licences. let raw_tier = if dm.tier.is_empty() { tier } else { dm.tier.as_str() }; let (tier_label, upgrade): (&str, &str) = match raw_tier { "homelab" => ("Homelab", "Upgrade to Homelab Plus (£29/mo, 25 hosts) at https://wolfstack.org/enterprise.php"), "homelab_plus" => ("Homelab Plus", "Upgrade to Team (£149/mo, 150 hosts) at https://wolfstack.org/enterprise.php"), "team" => ("Team", "Upgrade to Enterprise (unlimited hosts) at https://wolfstack.org/enterprise-contact.php"), other => (other, "Contact sales@wolf.uk.com to raise the cap"), }; Some(serde_json::json!({ "message": format!( "Host added — but your cluster now exceeds the {} tier ({} of {} hosts). {}", tier_label, current + 1, cap, upgrade ), "tier": raw_tier, "max_nodes": cap, "current_nodes": current + 1, "feature": "host_cap", })) } else { None } } else { None } } else { None }; let node_type = body.node_type.as_deref().unwrap_or("wolfstack"); if node_type == "proxmox" { return HttpResponse::Gone().json(serde_json::json!({ "error": "Proxmox API nodes have been deprecated, please install WolfStack on each node and then add them as WolfStack nodes to the main cluster — see our install page at https://wolfstack.org/download.php" })); } let port = body.port.unwrap_or(8553); let cluster_name = body.cluster_name.clone(); // Validate join token against the remote server let join_token = body.join_token.clone().unwrap_or_default(); if join_token.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Join token is required. Get it from the remote server's dashboard." })); } // Cluster-join hardening: the operator must prove they control the // TARGET node by supplying its admin username+password, which the // target verifies against its own auth. We forward them over the // existing TLS inter-node channel via the POST join-handshake; they // are NEVER logged or persisted on this master. let target_admin_username = body.target_admin_username.clone().unwrap_or_default(); let target_admin_password = body.target_admin_password.clone().unwrap_or_default(); if target_admin_username.trim().is_empty() || target_admin_password.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "The target node's admin username and password are required \ (proves you control the server you're adding)." })); } // Call the remote server's authenticated join handshake. This replaces // the old token-only GET verify-token round-trip; the target now also // verifies the admin credentials and hard-blocks a silent re-cluster. let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&body.address, port, "/api/cluster/join-handshake"); let handshake_body = serde_json::json!({ "token": join_token, "admin_username": target_admin_username, "admin_password": target_admin_password, "cluster_name": cluster_name, // So the joining node can seed US (the master) into its own registry by // our source IP — the fix for the membership split (wabil 2026-06-27). "master_port": state.cluster.port, "master_self_id": state.cluster.self_id, }); let mut last_error = String::new(); let mut verified = false; let mut cluster_fingerprint: Option = None; let mut bootstrap_grant: Option = None; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(8)) .json(&handshake_body) .send().await { Ok(resp) => { // Map the target's reqwest status into actix's StatusCode so // the operator sees the same code (e.g. 409 for the // already-in-cluster hard-block). The two crates' StatusCode // types differ; bridge via the raw u16. let http_status = actix_web::http::StatusCode::from_u16(resp.status().as_u16()) .unwrap_or(actix_web::http::StatusCode::BAD_GATEWAY); if let Ok(data) = resp.json::().await { if data.get("valid").and_then(|v| v.as_bool()) == Some(true) { cluster_fingerprint = data.get("cluster_fingerprint") .and_then(|v| v.as_str()).map(|s| s.to_string()); // Grant authorising the secret push below (lets a node // with its own secret adopt the fleet secret). bootstrap_grant = data.get("bootstrap_grant") .and_then(|v| v.as_str()).map(|s| s.to_string()); verified = true; break; } else { // Surface the target's specific refusal (bad token, // bad admin creds, or the already-in-cluster // hard-block) directly to the operator, preserving // the target's HTTP status so the frontend can // distinguish the override path (409). let err_msg = data.get("error").and_then(|v| v.as_str()) .unwrap_or("Join handshake rejected").to_string(); let mut out = serde_json::json!({ "error": err_msg }); if let Some(obj) = out.as_object_mut() { if let Some(already) = data.get("already_in_cluster") { obj.insert("already_in_cluster".to_string(), already.clone()); } if data.get("override_required").and_then(|v| v.as_bool()) == Some(true) { obj.insert("override_required".to_string(), serde_json::json!(true)); } } return HttpResponse::build(http_status).json(out); } } // Got a response but couldn't parse — try next URL if !last_error.is_empty() { last_error.push_str(" | "); } last_error.push_str(&format!("Unparseable response from {}", url)); } Err(e) => { // Accumulate EVERY attempt's failure. Reporting only the last // one showed the legacy plain-http fallback's error and hid // that https (tried FIRST) had already failed — operators // reasonably concluded WolfStack "uses http instead of https" // (masterpier, 2026-07-03). if !last_error.is_empty() { last_error.push_str(" | "); } last_error.push_str(&format!("{}: {}", url, e)); // Connection failed — try next URL } } } if !verified { return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("Cannot reach remote server at {}:{}. Tried every scheme — {}", body.address, port, last_error) })); } // Check for WolfNet IP conflicts before adding the node. // Fetch the remote node's status to get its wolfnet_ips, then compare // against all IPs known in this cluster (local + remote via route cache). let status_urls = build_node_urls(&body.address, port, "/api/agent/status"); let cluster_secret = crate::auth::load_cluster_secret(); let default_secret = crate::auth::default_cluster_secret(); let mut remote_wolfnet_ips: Vec = Vec::new(); // Also capture the joining node's own identity (its self_id `ws-…` and // hostname) so we can reconcile a reimaged node against any stale // pre-reimage registry entry once it's added (see reconciliation below). let mut remote_self_id = String::new(); let mut remote_hostname = String::new(); for url in &status_urls { // Try the active cluster secret first, then the default (new node may not have received custom secret yet) for secret in [&cluster_secret, &default_secret.to_string()] { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(secret) .send().await && resp.status().is_success() { if let Ok(data) = resp.json::().await { // `/api/agent/status` returns an externally-tagged // AgentMessage — every field lives under "StatusReport" // ({"StatusReport": {…}}), NOT at the top level. Reach // into that envelope (raw-object fallback should the // format ever change). Reading the top level returned // None for everything, which also left the wolfnet-IP // conflict check below dormant (AstroMando #3, // 2026-06-27). let sr = data.get("StatusReport").unwrap_or(&data); // Reservations, not routes: a container that is // stopped on the joining node still owns its IP, and // letting it join against an address another member // routes is the double-claim we refuse. Nodes older // than v25.25.3 send no reserved list and their // `wolfnet_ips` IS the full set. if let Some(ips) = sr.get("wolfnet_reserved_ips") .and_then(|v| v.as_array()) .filter(|a| !a.is_empty()) .or_else(|| sr.get("wolfnet_ips").and_then(|v| v.as_array())) { remote_wolfnet_ips = ips.iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) .collect(); } if remote_self_id.is_empty() && let Some(s) = sr.get("node_id").and_then(|v| v.as_str()) { remote_self_id = s.to_string(); } if remote_hostname.is_empty() && let Some(h) = sr.get("hostname").and_then(|v| v.as_str()) { remote_hostname = h.to_string(); } } break; } } if !remote_wolfnet_ips.is_empty() { break; } } if !remote_wolfnet_ips.is_empty() { // WolfNet-IP conflict check. Reject only when an IP the joining node // reports is already routed to a DIFFERENT node. The cluster-wide // IP→owner route cache is the authoritative map; an IP it attributes // to the joining node's own offline stale entries (a reimaged node // reusing its static IP) is its own footprint, not a conflict, and an // IP with no known owner is left alone (fail-open). This narrowness is // deliberate: the check was dormant for ages (wrong JSON envelope), so // anything short of a CONFIRMED foreign owner must not start rejecting // joins — least of all the reimage rejoin that #3 exists to support. let route_owner = containers::WOLFNET_ROUTES.lock().unwrap().clone(); let conflict_cluster = cluster_name.clone() .unwrap_or_else(|| "WolfStack".to_string()); let all_nodes = state.cluster.get_all_nodes(); // Only a route owned by a node that's ACTUALLY in the registry right now // counts — a deleted node's stale cache entry must not block a re-add. let live_addrs: std::collections::HashSet = all_nodes.iter() .map(|n| n.address.clone()) .collect(); let own_stale_addrs: std::collections::HashSet = all_nodes.iter() .filter(|n| !n.is_self && !n.online && node_is_returning_identity(n, &remote_self_id, &remote_hostname, &conflict_cluster)) .map(|n| n.address.clone()) .collect(); let conflicts = wolfnet_ip_conflicts( &remote_wolfnet_ips, &route_owner, &live_addrs, &own_stale_addrs, &body.address, ); if !conflicts.is_empty() { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!( "Cannot join node: WolfNet IP conflict — {} is already in use by another node in this cluster. \ Change the node's IP in /etc/wolfnet/config.toml and restart wolfnet before joining.", conflicts.join(", ") ) })); } } // Block duplicate nodes — check if a node with this address:port already exists let existing_nodes = state.cluster.get_all_nodes(); for existing in &existing_nodes { if existing.address == body.address && existing.port == port { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!( "A node at {}:{} already exists in the cluster (hostname: '{}', id: '{}'). \ Remove the existing node first if you want to re-add it.", body.address, port, existing.hostname, existing.id ) })); } } let id = state.cluster.add_server(body.address.clone(), port, cluster_name.clone()); // ── Join-time identity reconciliation (AstroMando #3, 2026-06-27) ── // A reimaged node returns with a NEW self_id (ws-…). The duplicate-block // above only rejects a SAME address:port re-add, so an operator re-adding // the node at its new address leaves the pre-reimage entry orphaned: // offline forever, yet still carrying this node's WolfRun instances. // WolfRun would then report those workloads "running" on a node that no // longer exists and schedule replacements against a dead id. Collapse any // such stale entry into the one we just added. // // Conservative match — a candidate must be OFFLINE, in the SAME cluster, // not the entry we just created, and the same physical node either by // self_id (an unchanged identity that merely moved address) OR by hostname // (the reimage case, where the self_id changed). A live entry is never // touched, so two genuinely-distinct online nodes can't be merged here. if !remote_hostname.is_empty() || !remote_self_id.is_empty() { let new_cluster = cluster_name.clone() .or_else(|| state.cluster.get_node(&id).and_then(|n| n.cluster_name)) .unwrap_or_else(|| "WolfStack".to_string()); let stale: Vec = state.cluster.get_all_nodes() .into_iter() .filter(|n| n.id != id && !n.is_self && !n.online) .filter(|n| node_is_returning_identity(n, &remote_self_id, &remote_hostname, &new_cluster)) .collect(); if stale.len() > 1 { // More than one stale match is a registry anomaly (e.g. two // offline entries sharing this hostname) — collapse them all but // make it visible so an operator can investigate a mis-set name. tracing::warn!(target: "add_node", "Returning node '{}' matched {} stale registry entries — collapsing all into {}", remote_hostname, stale.len(), id); } for old in &stale { let moved = state.wolfrun.remap_node_id(&old.id, &id); state.cluster.remove_server(&old.id); tracing::info!(target: "add_node", "Reconciled returning node '{}' ({} → {}): migrated {} WolfRun instance(s), removed stale offline entry", remote_hostname, old.id, id, moved); } } // Push our cluster secret to the new node — UNCONDITIONALLY, even // when we're still on the built-in default. The "always push" // semantic closes the Stage-2 new-cluster-formation corner case: // // Without it, joining a freshly-installed new-code node (which fired // Stage 2 and has its own per-install secret Y) to an existing // default-using cluster left the new node's secret unchanged. The // cluster could poll the new node (Y-node accepted our default via // Stage 5 default-acceptance), but the new node's outbound polls // signed with Y were rejected by the cluster — Y matched neither // our in-memory secret, the default, nor our on-disk secret. // // With "always push": the new node receives our secret, writes it to // /etc/wolfstack/custom-cluster-secret. On the new node's next // restart, its in-memory state aligns to our value and both // directions of polling authenticate cleanly. Operator action // required: restart wolfstack on the newly-joined node after // add_node returns. The push works regardless of whether our active // is default or a rotated value. // // The new node is freshly installed: its require_auth accepts any // of {its own per-install Stage-2 secret, our default, its on-disk}. // We don't know its per-install value, so we try TWO bootstrap // credentials in order: // 1. our `state.cluster_secret` — works if the new node was // pre-aligned out-of-band (operator scp'd the secret before // joining), OR if our active secret is the default (since the // new node accepts default by default). // 2. the hardcoded default — the original bootstrap path. Always // works on a new node that hasn't set // WOLFSTACK_REJECT_DEFAULT_SECRET=1. // If both fail (operator set the reject env flag on the new node // before joining) the operator must align secrets manually. let active_secret = crate::auth::load_cluster_secret(); { let addr = body.address.clone(); let secret = active_secret; let our_secret = state.cluster_secret.clone(); // Single-use grant from the handshake — lets the receiver adopt the // fleet secret even if it currently holds its own (the X-WolfStack- // Secret attempts below would otherwise be rejected, leaving it // divergent and its resources invisible to the cluster). let grant = bootstrap_grant.clone(); tokio::spawn(async move { let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&addr, port, "/api/cluster/secret/receive"); for auth_value in [our_secret.as_str(), crate::auth::default_cluster_secret()] { let mut pushed = false; for url in &urls { // Only attach the bootstrap grant on the TLS (https) leg — // never on the plaintext-http fallback. Capturing the grant // then requires breaking TLS, at which point the secret in // the same body is already exposed, so the grant adds no // marginal on-wire risk. (build_node_urls puts https first; // the http legs are the WolfNet-overlay and last-resort // plaintext fallbacks.) let leg_grant = if url.starts_with("https://") { grant.clone() } else { None }; // `bootstrap: true` tells the receiving node "this is a // first-time join; safe to self-restart so the new // secret takes effect in-memory immediately". Old-code // receivers ignore the field (serde_json::Value // parsing) and revert to "manual restart required". if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(auth_value) .json(&serde_json::json!({ "secret": secret, "bootstrap": true, "bootstrap_grant": leg_grant, })) .send() .await { let success = resp.status().is_success(); let _ = resp.bytes().await; if success { pushed = true; break; } } } if pushed { break; } } }); } // C1-Fix-2: Push the cluster_name to the new node so it KNOWS which // cluster it's in. Pre-fix, the new node had no way to learn its // cluster name except via gossip (which was broken — see agent/mod.rs // gossip ID-namespace mismatch fix). Operator-visible symptom of the // bug was the per-node WolfRouter showing "this node is in cluster // `WolfStack`" (the hardcoded fallback) regardless of actual cluster. if let Some(ref name) = cluster_name { // Record the durable intent BEFORE the opportunistic push below, // matching update_node_settings. The push is best-effort: a node that // is unreachable, mid-bootstrap-restart, or still negotiating its // secret can burn all five attempts and end up with no cluster name. // The retroactive heal sweep used to paper over that (and caused the // v25.5.5 identity-flapping bug doing it); the intent replaces it // properly — sweep_identity_intents re-pushes until the owner // self-reports the name, then clears the intent. It also keeps a // gossip round from reverting our local record while the new node is // still converging (pending-intent guard in agent::poll_remote_nodes). let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); crate::agent::record_identity_intent(&id, None, Some(name.clone()), ts); let addr = body.address.clone(); let our_secret = state.cluster_secret.clone(); let cluster_name_val = name.clone(); tokio::spawn(async move { // The concurrent secret push may trigger a bootstrap-restart // on the new node (cluster_secret_receive auto-restarts if // `bootstrap: true` + secret_actually_changed + no peers). // The restart takes 3-8 seconds. Retry the cluster-name // push a few times with backoff so we don't lose the push // to the restart window. Without retry the new node would // come back up with no cluster name and default to // "(not yet configured)" until the operator manually re-pushed. let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&addr, port, "/api/agent/cluster-name"); let payload = serde_json::json!({ "cluster_name": cluster_name_val }); for attempt in 0..5u32 { if attempt > 0 { // 2s, 4s, 6s, 8s — covers a ~20s restart window. tokio::time::sleep(std::time::Duration::from_secs(2 * attempt as u64)).await; } // Same two-credential bootstrap pattern as the secret push. for auth_value in [our_secret.as_str(), crate::auth::default_cluster_secret()] { let mut pushed = false; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(auth_value) .json(&payload) .send() .await { let success = resp.status().is_success(); let _ = resp.bytes().await; if success { pushed = true; break; } } } if pushed { return; } } } tracing::warn!(target: "add_node", "cluster-name push to {} did not succeed after 5 attempts; \ operator may need to re-set cluster name manually", addr); }); } // Audit + alert the join on the MASTER side too (the target audited // its own acceptance; this records who initiated it from here). { let actor = &add_actor; cluster_join_audit( &state, actor, "warning", "Node added to cluster", &format!("Added {}:{} into cluster '{}' (fingerprint {})", body.address, port, cluster_name.clone().unwrap_or_default(), cluster_fingerprint.clone().unwrap_or_else(|| "n/a".into())), "", ); crate::alerting::send_local_alert( crate::alerting::AlertCategory::Posture, "Node added to cluster", &format!("{} added node {}:{} to cluster '{}'.", actor, body.address, port, cluster_name.clone().unwrap_or_default()), ).await; } let mut response = serde_json::json!({ "id": id, "address": body.address, "port": port, "node_type": "wolfstack", "cluster_name": cluster_name, "cluster_fingerprint": cluster_fingerprint, }); if let Some(warning) = cap_warning && let Some(obj) = response.as_object_mut() { obj.insert("warning".to_string(), warning); } HttpResponse::Ok().json(response) } /// DELETE /api/nodes/{id} — remove a server pub async fn remove_node(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // Capture the node's identity BEFORE removal so we can also evict it from // every node's WolfNet peer list. Without this the deleted node lingers in // /etc/wolfnet/config.toml on each remaining peer and shows up forever as an // unreachable peer (wabil 2026-06-17). Cluster-sync's prune pass would // eventually catch it, but a delete should clean up immediately. let removed_node = state.cluster.get_node(&id); if state.cluster.remove_server(&id) { // The Inbox aggregation caches its peer fan-out for 30 s and keys the // per-node status list off cluster membership. Without this, a node // the operator just deleted keeps appearing in the Inbox (and in its // "may be incomplete" warning) until the cache expires. invalidate_cluster_cache(&state); // Evict from THIS node's WolfNet config right away (synchronous). // Best-effort: "not found" is fine, and a WolfNet-less node has nothing // to evict. if let Some(ref n) = removed_node && !n.hostname.is_empty() { let _ = networking::remove_wolfnet_peer(&n.hostname); } // Broadcast deletion to all other online nodes so they don't gossip it back let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let delete_id = id.clone(); let peer_name = removed_node.as_ref() .map(|n| n.hostname.clone()) .filter(|h| !h.is_empty()); tokio::spawn(async move { let client = &*API_HTTP_CLIENT; for node in &nodes { if node.is_self || !node.online { continue; } let urls = build_node_urls(&node.address, node.port, &format!("/api/nodes/{}", delete_id)); for url in &urls { if let Ok(resp) = client.delete(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .send() .await { let _ = resp.bytes().await; break; // Success, no need to try next URL } } // Also evict the deleted node from this peer's WolfNet config — // same name-keyed DELETE that cluster-sync's prune pass uses. if let Some(ref pname) = peer_name { let purls = build_node_urls(&node.address, node.port, "/api/networking/wolfnet/peers"); let payload = serde_json::json!({ "name": pname }).to_string(); for url in &purls { if let Ok(resp) = client.delete(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .header("Content-Type", "application/json") .body(payload.clone()) .send() .await { let _ = resp.bytes().await; break; } } } } }); HttpResponse::Ok().json(serde_json::json!({ "removed": true })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })) } } /// PATCH /api/nodes/{id}/settings — update node settings #[derive(Deserialize)] pub struct UpdateNodeSettings { pub hostname: Option, pub address: Option, pub port: Option, pub pve_token: Option, pub pve_fingerprint: Option, pub pve_cluster_name: Option, pub cluster_name: Option, pub login_disabled: Option, pub update_script: Option, /// Site tag — see `agent::Node::site`. Empty string clears any /// previously-set tag (falls back to auto-derived). Frontend /// sends this from the "Site" field on the node settings card. pub site: Option, /// Friendly display name — see `agent::Node::display_name`. Empty /// string clears the override (UI falls back to the OS hostname). /// This is the operator-set "node name" from the fleet UI. #[serde(default)] pub display_name: Option, /// Tier roles — see `agent::Node::roles`. `Some([])` clears all roles /// (general-purpose node); `None` (field absent) leaves them unchanged. #[serde(default)] pub roles: Option>, /// Migration/bulk-transfer address override — see /// `agent::Node::migration_address`. Empty string clears it (migration /// falls back to `address`); `None` (field absent) leaves it unchanged. /// Frontend sends this from the "Migration address" field on the node /// settings card so operators can pin migration onto a dedicated NIC. #[serde(default)] pub migration_address: Option, /// Whether peers accept operator actions forwarded by this node. /// Applied locally and pushed to every peer (see /// `cluster_node_policy_receive`). #[serde(default)] pub manager: Option, /// Low-traffic poll interval in seconds — see /// `agent::Node::poll_interval_secs`. Must be one of /// `agent::POLL_INTERVAL_CHOICES`; 10 restores the default. `None` (field /// absent) leaves it unchanged. #[serde(default)] pub poll_interval_secs: Option, } pub async fn update_node_settings(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let id = path.into_inner(); // Same length cap as the inter-node `set_site` endpoint. Admins // editing via PATCH must not be able to write a longer value // than the propagation push will accept. if let Some(ref s) = body.site && s.len() > 64 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "site tag too long (max 64 chars)" })); } let fp = if body.pve_fingerprint.is_some() { Some(body.pve_fingerprint.clone()) } else { None }; // Support updating both pve_cluster_name (for compat) and generic cluster_name let cluster_name = body.cluster_name.clone().or(body.pve_cluster_name.clone()); // Length cap on the display name (same as the agent receiver). if let Some(ref dn) = body.display_name && dn.len() > 64 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "display name too long (max 64 chars)" })); } if let Some(secs) = body.poll_interval_secs && !crate::agent::POLL_INTERVAL_CHOICES.contains(&secs) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("poll interval must be one of {:?} seconds", crate::agent::POLL_INTERVAL_CHOICES) })); } if state.cluster.update_node_settings( &id, body.hostname.clone(), body.address.clone(), body.port, body.pve_token.clone(), fp, cluster_name.clone(), body.login_disabled, body.update_script.clone(), body.site.clone(), body.display_name.clone(), body.migration_address.clone(), body.manager, ) { // NOTE: this PATCH edits ONE node only. Changing `cluster_name` here // MOVES this single node to a (possibly new) cluster — it does NOT // rename the whole cluster or drag the other members along (that was // the old "creates a mess" behaviour). Renaming a cluster as a group, // with the status-page / WolfRun data migration, is a separate // operation: POST /api/clusters/{old}/rename (cluster_rename_handler). // Propagate site to remote WolfStack node so its own // StatusReport carries the new tag immediately — without // this the next gossip tick would still carry the peer's // old site value (or None) and cluster-sync decisions would // lag by a poll cycle. // // Asymmetric-state caveat: gossip only ever carries each // node's OWN site outward, never the master's view of a // remote inward. If this push fails (remote temporarily // unreachable) the remote's self-knowledge stays stale and // its NEXT direct StatusReport will gossip the old value. // The master's local view is still correct, so cluster-sync // initiated from the master uses the new value — but a sync // initiated from the unreached remote would not. We log on // total failure so operators have a trace; no retry queue. if let Some(ref site) = body.site { let node = state.cluster.get_node(&id); if let Some(node) = node && !node.is_self && node.node_type == "wolfstack" { let secret = state.cluster_secret.clone(); let address = node.address.clone(); let port = node.port; let hostname = node.hostname.clone(); let site_val = site.clone(); tokio::spawn(async move { let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&address, port, "/api/settings/site"); let payload = serde_json::json!({ "site": site_val }); let mut delivered = false; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .header("Content-Type", "application/json") .body(payload.to_string()) .send() .await { let _ = resp.bytes().await; delivered = true; break; } } if !delivered { tracing::warn!( "site propagation push to '{}' ({}:{}) failed on all URLs — remote will keep its previous site until next direct StatusReport", hostname, address, port ); } }); } } // Roles: authoritative on the OWNING node, exactly like site. Update // the master's in-memory view immediately (so tier fan-outs from the // control node see it at once), then either persist locally (self) or // push to the remote's /api/settings/roles. Unknown tokens are dropped. let mut policy_push_failed: Vec = Vec::new(); if let Some(manager) = body.manager { // Policy is about the target node, enforced by every OTHER node — // push it to all of them as this operator's forwarded action. let target_id = state.cluster.get_node(&id) .and_then(|n| n.self_id.clone().filter(|s| !s.is_empty())) .unwrap_or_else(|| id.clone()); let peers: Vec<(String, u16, String)> = state.cluster.get_all_nodes().into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack") .map(|n| (n.address.clone(), n.port, n.hostname.clone())) .collect(); // Awaited, not spawned: the operator must learn which peers did // NOT take the policy. A node that was itself demoted cannot // re-promote itself (its push is refused as a non-manager) — that // is correct, and the operator has to hear it, not find it in a // log. Change it from a manager node instead. let payload = serde_json::json!({ "node_id": target_id, "manager": manager }); for (address, port, hostname) in peers { let mut delivered = false; let mut last = String::new(); for url in build_node_urls(&address, port, "/api/cluster/node-policy") { match API_HTTP_CLIENT.post(&url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&state.cluster_secret) .header("X-WolfStack-Proxied", "1") .header("X-WolfStack-Actor", &caller) .json(&payload) .send().await { Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); if status.is_success() { delivered = true; break; } last = serde_json::from_str::(&body).ok() .and_then(|v| v["error"].as_str().map(str::to_string)) .unwrap_or_else(|| format!("HTTP {}", status)); // A refusal is final; only try the next URL on transport failure. break; } Err(e) => { last = e.to_string(); } } } if !delivered { tracing::warn!("node policy push (manager={}) to '{}' ({}:{}) failed: {}", manager, hostname, address, port, last); policy_push_failed.push(serde_json::json!({ "node": hostname, "error": last })); } } } if let Some(ref roles_raw) = body.roles { let roles: Vec = roles_raw.iter().copied() .filter(|r| *r != crate::agent::NodeRole::Unknown) .collect::>() .into_iter() .collect(); // Only real WolfStack nodes carry tier roles — a Proxmox-type // node can't run DNS / mail / ingress subsystems, so refuse to // tag one (guards the fan-out from proxying an RPC it can't serve). let is_wolfstack = state.cluster.get_node(&id) .map(|n| n.node_type == "wolfstack") .unwrap_or(false); let is_self = if is_wolfstack { let mut nodes = state.cluster.nodes_write(); if let Some(node) = nodes.get_mut(&id) { node.roles = roles.clone(); node.is_self } else { false } } else { false }; if is_self { crate::agent::ClusterState::save_self_roles(&roles); } else if is_wolfstack && let Some(node) = state.cluster.get_node(&id) { let secret = state.cluster_secret.clone(); let (address, port, hostname) = (node.address.clone(), node.port, node.hostname.clone()); let payload = serde_json::json!({ "roles": roles }); tokio::spawn(async move { let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&address, port, "/api/settings/roles"); let mut delivered = false; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .header("Content-Type", "application/json") .body(payload.to_string()) .send().await { let _ = resp.bytes().await; delivered = true; break; } } if !delivered { tracing::warn!( "roles propagation push to '{}' ({}:{}) failed on all URLs — remote will re-assert its previous roles until next direct StatusReport", hostname, address, port ); } }); } } // Propagate login_disabled to remote node so it takes effect on their login page if let Some(disabled) = body.login_disabled { let node = state.cluster.get_node(&id); if let Some(node) = node && !node.is_self && node.node_type == "wolfstack" { let secret = state.cluster_secret.clone(); let address = node.address.clone(); let port = node.port; tokio::spawn(async move { let client = &*API_HTTP_CLIENT; let urls = build_node_urls(&address, port, "/api/settings/login-disabled"); let payload = serde_json::json!({ "login_disabled": disabled }); for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .header("Content-Type", "application/json") .body(payload.to_string()) .send() .await { let _ = resp.bytes().await; break; } } }); } } // Reliable propagation of identity edits (display name + cluster move) // to the OWNING remote node. The owner's self-report is authoritative, // so until it adopts the value the next 10s poll would revert it. We // record the intent (so an offline owner converges when it reconnects — // sweep_identity_intents re-pushes until confirmed), push synchronously, // and tell the UI whether it applied now or was queued. let mut queued = false; let want_display = body.display_name.clone(); let want_cluster = body.cluster_name.clone().or(body.pve_cluster_name.clone()); if (want_display.is_some() || want_cluster.is_some()) && let Some(node) = state.cluster.get_node(&id) && !node.is_self && node.node_type == "wolfstack" { let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); // Record the durable intent first (so an offline/unreachable // owner converges via sweep_identity_intents on reconnect), // then fire the push in the background — never block the // actix worker on remote HTTP. `queued` is a best-effort // immediate signal from liveness; the sweep is the real // delivery guarantee. crate::agent::record_identity_intent(&id, want_display.clone(), want_cluster.clone(), ts); queued = !node.online; let intent = crate::agent::IdentityIntent { display_name: want_display, cluster_name: want_cluster, ts, }; let secret = state.cluster_secret.clone(); tokio::spawn(async move { let _ = crate::agent::push_identity_to_node(&node, &intent, &secret).await; }); } // Low-traffic poll interval: owned by the node it describes, like // roles. Set here for self; for a remote, push to the owner so it // slows ITS polling and advertises the interval to every other peer, // and mirror it into this node's view once the owner accepts. Awaited, not spawned: an owner // that didn't take it would re-advertise its old interval on its // next report and silently undo the edit, so the operator must hear. let mut poll_interval_error: Option = None; if let Some(secs) = body.poll_interval_secs { let target = state.cluster.get_node(&id).filter(|n| n.node_type == "wolfstack"); match target { Some(node) if node.is_self => { if let Err(e) = state.cluster.set_self_poll_interval(Some(secs)) { poll_interval_error = Some(format!( "applied for now but not saved ({}), so it will return to the default after a restart", e)); } } Some(node) => { let payload = serde_json::json!({ "poll_interval_secs": secs }); let mut last = String::from("unreachable"); let mut delivered = false; for url in build_node_urls(&node.address, node.port, "/api/settings/poll-interval") { match API_HTTP_CLIENT.post(&url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&state.cluster_secret) .json(&payload) .send().await { Ok(resp) => { let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if status.is_success() { delivered = true; break; } last = serde_json::from_str::(&text).ok() .and_then(|v| v["error"].as_str().map(str::to_string)) .unwrap_or_else(|| format!("HTTP {}", status)); // A 404 is a peer too old to know the endpoint — // final, like any other refusal. break; } Err(e) => { last = e.to_string(); } } } // Mirror it locally only once the owner took it — so this // node slows its own polling of that peer at once, and a // refused edit never shows as applied in this node's view. if delivered && let Some(n) = state.cluster.nodes_write().get_mut(&id) { n.poll_interval_secs = crate::agent::normalize_poll_interval(Some(secs)); } if !delivered { tracing::warn!("poll interval push ({}s) to '{}' ({}:{}) failed: {}", secs, node.hostname, node.address, node.port, last); poll_interval_error = Some(format!( "'{}' did not accept it ({}). The node must be online and running a WolfStack version with low-traffic mode; until then it keeps its previous interval", node.display_name.as_deref().unwrap_or(&node.hostname), last)); } } None => { poll_interval_error = Some("only WolfStack nodes have a poll interval".to_string()); } } state.cluster.save_nodes(); } HttpResponse::Ok().json(serde_json::json!({ "updated": true, "queued": queued, "policy_push_failed": policy_push_failed, "poll_interval_error": poll_interval_error, })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })) } } /// POST /api/agent/cluster-name — accept cluster name update from admin node pub async fn agent_set_cluster_name(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } if let Some(name) = body.get("cluster_name").and_then(|v| v.as_str()) { let old = { let mut nodes = state.cluster.nodes_write(); let old = nodes.get(&state.cluster.self_id).and_then(|n| n.cluster_name.clone()); if let Some(n) = nodes.get_mut(&state.cluster.self_id) { n.cluster_name = Some(name.to_string()); } old }; crate::agent::ClusterState::save_self_cluster_name(name); // If this push is a cluster RENAME (our name actually changed), bring // this node's local cluster-tagged stores (TrueNAS/Unraid/Galera/ // WolfScale/WG-bridge) along. A node with no assignment displayed // under the default "WolfStack" group, so its local tags were created // with that label. Sync file I/O — off the worker. let old_label = old.unwrap_or_else(|| "WolfStack".to_string()); if !crate::agent::cluster_eq(Some(&old_label), Some(name)) { let new_name = name.to_string(); let _ = web::block(move || { crate::agent::migrate_local_cluster_tags(&old_label, &new_name) }).await; } HttpResponse::Ok().json(serde_json::json!({ "updated": true, "cluster_name": name })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": "cluster_name required" })) } } /// POST /api/agent/display-name — accept a friendly display-name update from /// the admin node. Updates the in-memory self node immediately (so the next /// 2s status-cache rebuild self-reports it) and persists it. Empty string /// clears the override (UI falls back to the OS hostname). Mirrors /// `agent_set_cluster_name`. pub async fn agent_set_display_name(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } match body.get("display_name").and_then(|v| v.as_str()) { Some(name) => { if name.len() > 64 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "display name too long (max 64 chars)" })); } let mut nodes = state.cluster.nodes_write(); if let Some(n) = nodes.get_mut(&state.cluster.self_id) { n.display_name = if name.is_empty() { None } else { Some(name.to_string()) }; } drop(nodes); crate::agent::ClusterState::save_self_display_name(name); HttpResponse::Ok().json(serde_json::json!({ "updated": true, "display_name": name })) } None => HttpResponse::BadRequest().json(serde_json::json!({ "error": "display_name required" })), } } #[derive(serde::Deserialize)] pub struct ClusterRenameRequest { pub new_name: String, } /// POST /api/clusters/{old}/rename — rename a WHOLE cluster (every member /// node), migrating cluster-scoped status-page + WolfRun data, and reliably /// pushing the new name to each member's owner. This is the GROUP rename, /// distinct from MOVING one node (PATCH /api/nodes/{id}/settings with /// cluster_name, which only touches that node). Splitting the two is what /// fixes the old "moving a node renames its whole cluster" mess. pub async fn cluster_rename_handler( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let old_name = path.into_inner(); let new_name = body.new_name.trim().to_string(); if new_name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "new cluster name required" })); } if new_name.len() > 64 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "cluster name too long (max 64 chars)" })); } if new_name == old_name { return HttpResponse::Ok().json(serde_json::json!({ "renamed": 0, "queued": false })); } // Migrate cluster-scoped data so monitors / pages / incidents / WolfRun // services follow the rename (relocated here from the per-node PATCH). { let mut config = state.statuspage.config.write().unwrap(); let sp_count = config.rename_cluster(&old_name, &new_name); if sp_count > 0 { let _ = config.save(); tracing::info!("Cluster rename: {} status-page items '{}' -> '{}'", sp_count, old_name, new_name); } } let wr_count = state.wolfrun.rename_cluster(&old_name, &new_name); if wr_count > 0 { tracing::info!("Cluster rename: {} WolfRun services '{}' -> '{}'", wr_count, old_name, new_name); } // Gateways (SMB/NFS shares) carry a cluster tag too. Their store // replicates fleet-wide on its own, so re-tag once here and push — // every node converges without per-member work. let gw_count = { let mut store = state.gateways.write().unwrap_or_else(|e| e.into_inner()); let mut n = 0usize; for g in store.gateways.values_mut() { if !g.cluster.is_empty() && g.cluster.eq_ignore_ascii_case(&old_name) { g.cluster = new_name.clone(); n += 1; } } if n > 0 { let _ = store.save(); } n }; if gw_count > 0 { invalidate_gateway_cluster_cache(&state); push_to_peers(&state).await; tracing::info!("Cluster rename: {} gateways '{}' -> '{}'", gw_count, old_name, new_name); } // This node's own cluster-tagged stores (TrueNAS/Unraid/Galera/WolfScale/ // WG-bridge). Remote members migrate their own when the new name reaches // them (push receiver or gossip self-adoption). Sync file I/O — off the // worker. { let (o, nn) = (old_name.clone(), new_name.clone()); let _ = web::block(move || crate::agent::migrate_local_cluster_tags(&o, &nn)).await; } // Every member: update the local view, then reliably push the new name to // its owner (intent + sweep), so none of them re-assert the old name. // Case-insensitive match: a rename of "Minio" must also catch a node whose // stored name drifted to "minio" (same cluster) and unify them all to the // operator's typed `new_name` — this is what heals an existing case split. // cluster_rename_member_matches: case-insensitive name match, PLUS nodes // with NO cluster assigned when renaming the default "WolfStack" group — // they display under that group everywhere, so the rename must take them // along or the group visibly splits. let members: Vec = state.cluster.get_all_nodes().into_iter() .filter(|n| crate::agent::cluster_rename_member_matches(n.cluster_name.as_deref(), &old_name)) .collect(); let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); let mut renamed = 0usize; let mut queued = false; for node in members { state.cluster.update_node_settings( &node.id, None, None, None, None, None, Some(new_name.clone()), None, None, None, None, None, None, ); renamed += 1; if !node.is_self && node.node_type == "wolfstack" { // Durable intent + background push — never block the worker on a // member that's slow/unreachable (could be minutes across N nodes). crate::agent::record_identity_intent(&node.id, None, Some(new_name.clone()), ts); if !node.online { queued = true; } let intent = crate::agent::IdentityIntent { display_name: None, cluster_name: Some(new_name.clone()), ts, }; let secret = state.cluster_secret.clone(); tokio::spawn(async move { let _ = crate::agent::push_identity_to_node(&node, &intent, &secret).await; }); } } HttpResponse::Ok().json(serde_json::json!({ "renamed": renamed, "queued": queued })) } /// POST /api/cluster/control-plane — receive a peer's control-plane bundle. /// Converges cluster membership (so logging into ANY node shows the whole /// fleet) and replicates WolfStack users + auth config last-write-wins. /// Cluster-secret authed (an inter-node call, NOT a user session) — it carries /// password hashes, the same trust boundary the rest of the gossip uses. pub async fn cluster_control_plane_receive( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } // The sender advertises its bind address (often 0.0.0.0) for itself; learn // its REAL address from the connection source IP so the hub "main" is // reachable from every other node (regression: secondaries saw all nodes // except main). Use the raw TCP peer address, NOT X-Forwarded-For — this is // a direct, cluster-secret-authed node→node call; trusting a client header // for the source IP would let a peer spoof another node's address. Inter- // node traffic is not reverse-proxied. // to_canonical: a dual-stack [::] listener reports a v4 peer as // ::ffff:a.b.c.d — storing that as the node's learned address would // produce undialable https://[::ffff:a.b.c.d] URLs fleet-wide. let sender_addr = req.peer_addr().map(|a| a.ip().to_canonical().to_string()); let detail = crate::agent::apply_control_plane_bundle(&state.cluster, &body, sender_addr); HttpResponse::Ok().json(serde_json::json!({ "applied": true, "detail": detail })) } /// Fire a one-shot control-plane replication push after a local user/auth /// change so peers converge within seconds instead of waiting for the periodic /// sweep. Best-effort and non-blocking. pub fn trigger_control_plane_push(state: &web::Data) { let cluster = state.cluster.clone(); tokio::spawn(async move { let secret = crate::auth::load_cluster_secret(); crate::agent::sweep_replicate_control_plane(cluster, secret).await; }); } /// POST /api/agent/wolfnet-routes — accept WolfNet route updates from orchestrator /// Used to push VIP routes to all nodes so they can reach service VIPs via the orchestrator pub async fn agent_set_wolfnet_routes(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } if let Some(routes) = body.get("routes").and_then(|v| v.as_object()) { let mut route_map = std::collections::HashMap::new(); for (k, v) in routes { if let Some(ip) = v.as_str() { route_map.insert(k.clone(), ip.to_string()); } } let changed = crate::containers::update_wolfnet_routes(&route_map); // Also add kernel routes so traffic for VIPs enters the wolfnet tunnel for vip in route_map.keys() { let _ = std::process::Command::new("ip") .args(["route", "replace", &format!("{}/32", vip), "dev", "wolfnet0"]) .output(); } HttpResponse::Ok().json(serde_json::json!({ "updated": changed, "routes": route_map.len() })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": "routes object required" })) } } /// POST /api/cluster/wolfnet-sync — reconcile the WolfNet peer list of the /// nodes in `node_ids` (one cluster): each node is peered with the others, /// and any peer in its config that is not one of those nodes is removed. /// Strictly scoped to the cluster passed in — other clusters are untouched. /// WolfNet itself is cluster-agnostic; WolfStack owns the cluster boundary. #[derive(Deserialize)] pub struct WolfNetSyncRequest { pub node_ids: Vec, } /// Do two WolfNet peer/host names refer to the same node? True for an exact /// match (case-insensitive) or a short-hostname-vs-FQDN pair (`immich` vs /// `immich.lan`). Deliberately NOT a substring test: the old `a.contains(b)` /// kept a stale `docker-immich` peer alive forever because it contains the live /// host `immich`, so cluster-sync's prune never removed it (wabil 2026-06-17). fn hostnames_same_node(a: &str, b: &str) -> bool { let a = a.trim().to_ascii_lowercase(); let b = b.trim().to_ascii_lowercase(); if a.is_empty() || b.is_empty() { return false; } if a == b { return true; } let a_short = a.split('.').next().unwrap_or(&a); let b_short = b.split('.').next().unwrap_or(&b); // Same leading label, but only when a dot is actually involved — two // distinct dotless names (`docker-immich` vs `immich`) never match here. a_short == b_short && (a.contains('.') || b.contains('.')) } /// Does registry entry `n` look like the same physical node as one that just /// (re)joined — for join-time identity reconciliation (AstroMando #3)? Matches /// within the same cluster on EITHER an unchanged self_id (the node merely /// moved address) OR the hostname (the reimage case, where the self_id is /// regenerated). This is purely the identity match; the caller still applies /// the offline / not-self / not-the-new-entry guards before collapsing. fn node_is_returning_identity(n: &crate::agent::Node, self_id: &str, hostname: &str, cluster: &str) -> bool { let same_cluster = n.cluster_name.as_deref().unwrap_or("WolfStack") .eq_ignore_ascii_case(cluster); if !same_cluster { return false; } let sid_match = !self_id.is_empty() && n.self_id.as_deref() == Some(self_id); let host_match = !hostname.is_empty() && hostnames_same_node(&n.hostname, hostname); sid_match || host_match } /// Of the WolfNet IPs a joining node reports, return the ones that GENUINELY /// conflict — already routed to a DIFFERENT, CURRENTLY-REGISTERED node. /// `route_owner` is the cluster-wide IP→owning-address map (WOLFNET_ROUTES); /// `live_addrs` are the addresses of nodes that are actually in the registry /// right now. A route is only a conflict when its owner is a live node — a /// stale route left in the cache by a DELETED node (its 60s prune hasn't run /// yet) must not block re-adding that IP, which is what falsely rejected a /// re-add after wabil deleted the whole cluster (2026-06-28). `own_stale_addrs` /// excludes the joining node's own offline reimage entries, and `joining_addr` /// is the address being added. Unknown / non-live owner → left alone /// (fail-open: this check stays narrow so it never rejects a legitimate join). fn wolfnet_ip_conflicts( remote_ips: &[String], route_owner: &std::collections::HashMap, live_addrs: &std::collections::HashSet, own_stale_addrs: &std::collections::HashSet, joining_addr: &str, ) -> Vec { let mut conflicts = Vec::new(); for ip in remote_ips { let bare = ip.split('/').next().unwrap_or(ip); if let Some(owner) = route_owner.get(bare) && live_addrs.contains(owner) && !own_stale_addrs.contains(owner) && owner != joining_addr { conflicts.push(bare.to_string()); } } conflicts } pub async fn wolfnet_sync_cluster(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let node_ids = &body.node_ids; if node_ids.len() < 2 { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Need at least 2 nodes to sync"})); } // Collect WolfNet info from each node. Each peer carries BOTH its // LAN address (`lan_address`, what the local WolfStack agent reports // as its bind/management address) AND its public IP if known. The // right endpoint to write into the WolfNet config depends on which // target node the config is going to — see `pick_wolfnet_endpoint` // below. The old design baked a single `endpoint` string per peer // and reused it for every target, which on klasSponsor's 14-node // cluster left the internet-only VPS with peer endpoints like // `10.10.10.30:9630` that route via lo and black-hole. #[derive(Clone)] struct NodeWnInfo { hostname: String, wolfnet_ip: String, public_key: String, /// WolfNet listen port (the daemon's own UDP port, distinct /// from the WolfStack API `port`). wolfnet_port: u16, is_self: bool, /// The agent's reported address (`node.address`) — typically a /// LAN IP, but for an internet-only node this is its public IP. lan_address: String, public_ip: Option, /// WolfStack API port — used to call back into this node when /// pushing peer entries to it. port: u16, /// Peers currently in this node's WolfNet config (name, allowed_ip). /// Used to prune entries that aren't members of this cluster. current_peers: Vec<(String, String)>, /// Operator-declared site tag (or None to auto-derive) — see /// `networking::effective_site` and `pick_wolfnet_endpoint`. /// Drives the LAN-vs-public endpoint decision per (target, peer) /// pair: same effective site → LAN dial; different → public. site: Option, } /// Extract (name, allowed_ip) for every peer in a /local-info response. fn extract_peers(info: &serde_json::Value) -> Vec<(String, String)> { info.get("peers").and_then(|v| v.as_array()).map(|arr| { arr.iter().filter_map(|p| { let name = p.get("name")?.as_str()?.to_string(); let ip = p.get("ip").and_then(|v| v.as_str()).unwrap_or("").to_string(); Some((name, ip)) }).collect() }).unwrap_or_default() } /// Pick the WolfNet endpoint string to write into `target`'s config /// for `peer`. `None` means "no static endpoint — let WolfNet learn /// it via roaming". /// /// Site-aware decision (klasSponsor 2026-05-29 multi-VLAN fix): /// * Both target and peer share an effective_site (operator-set /// or auto-derived from /24 of `lan_address`) → they're on /// the same physical LAN, so dial peer at its `lan_address`. /// That's the only configuration where the LAN address is /// actually reachable from the target. /// * Different sites (or one untagged in a way that can't match) /// → fall through to `decide_peer_endpoint` so the public-IP /// + safety-guards path applies for both LAN-side and /// public-side targets. Pre-Site, the LAN-target branch /// unconditionally wrote `peer.lan_address` — on klasSponsor's /// UniFi multi-VLAN cluster that meant target VLAN 10 dialed /// a peer at its VLAN 20 address (unreachable), wolfnet roamed /// to the public IP, then every reload reverted to the /// unreachable LAN — observable as the endpoint flapping /// between local and public. /// /// Backward-compat for single-LAN clusters: all nodes share a /24, /// so all auto-derived sites match, so the LAN branch fires /// exactly as before without any operator action. fn pick_wolfnet_endpoint(target: &NodeWnInfo, peer: &NodeWnInfo) -> Option { let t_site = crate::networking::effective_site(&target.site, &target.lan_address); let p_site = crate::networking::effective_site(&peer.site, &peer.lan_address); let same_site = matches!((t_site.as_deref(), p_site.as_deref()), (Some(a), Some(b)) if a == b); if same_site { return Some(format!("{}:{}", peer.lan_address, peer.wolfnet_port)); } // Different sites (or one without a site at all). Use the // shared decision function so the loop / NAT / loopback // guards apply identically with the auto-reconciler path. // Local wolfnet subnet is a proxy for target's (one cluster // = one wolfnet subnet in practice). let decision = crate::networking::decide_peer_endpoint( &target.lan_address, crate::networking::get_local_wolfnet_subnet(), Some(&peer.lan_address), peer.public_ip.as_deref(), peer.wolfnet_port, ); match decision { crate::networking::PeerEndpoint::Set(s) => Some(s), crate::networking::PeerEndpoint::Clear | crate::networking::PeerEndpoint::Preserve => None, } } let client = &*API_HTTP_CLIENT; let mut infos: Vec = Vec::new(); let mut errors: Vec = Vec::new(); // Same-LAN guard for the bind-all (0.0.0.0) address resolution below. // The RFC1918 /24 of every cluster node that already has a real address. // A node bound to 0.0.0.0 only substitutes its detected LAN IP for its // public IP when that LAN IP shares a /24 with another cluster node — // i.e. this genuinely is a single-LAN cluster (AstroMando's topology). // On a real multi-DC cluster no peer shares the bind-all node's private // /24, so we leave the public-IP value untouched and never trip the // behind-NAT endpoint guard for an inter-site link. let lan_prefix = |addr: &str| -> Option { let ip: std::net::Ipv4Addr = addr.parse().ok()?; let o = ip.octets(); let rfc1918 = o[0] == 10 || (o[0] == 172 && (16..=31).contains(&o[1])) || (o[0] == 192 && o[1] == 168); if !rfc1918 { return None; } Some(format!("{}.{}.{}", o[0], o[1], o[2])) }; let cluster_lan_prefixes: std::collections::HashSet = node_ids.iter() .filter_map(|nid| state.cluster.get_node(nid)) .filter_map(|n| lan_prefix(&n.address)) .collect(); // Scoped strictly to the cluster passed in `node_ids` — other clusters // are never examined or touched. for nid in node_ids { let node = match state.cluster.get_node(nid) { Some(n) => n, None => { errors.push(format!("Node {} not found", nid)); continue; } }; if node.node_type != "wolfstack" { errors.push(format!("{} is not a WolfStack node", node.hostname)); continue; } if node.is_self { // Get local info directly match networking::get_wolfnet_local_info() { Some(info) => { let hostname = info["hostname"].as_str().unwrap_or("").to_string(); let wolfnet_ip = info["address"].as_str().unwrap_or("").to_string(); let public_key = info["public_key"].as_str().unwrap_or("").to_string(); let listen_port = info["listen_port"].as_u64().unwrap_or(9600) as u16; if wolfnet_ip.is_empty() || public_key.is_empty() { errors.push(format!("{}: WolfNet not configured", node.hostname)); continue; } // The address WolfStack stored for THIS node (is_self) may // not be dialable on the LAN, which silently breaks WolfNet // for it. Three cases, all the same fix: // * bind-all start → 0.0.0.0 / 127.0.0.1 // * reached via a reverse proxy → a WAN HOSTNAME // (wabil's pm1 self-identified as "mydomain.mywire.org") // * added by its public IP → a WAN IP // In any of these, recording that value as the node's // lan_address poisons effective_site()/pick_wolfnet_endpoint // — the LAN peers get told to dial it at a WAN hostname/IP // behind NAT, its endpoint resolves to the WAN, and the mesh // to/from it goes dark (AstroMando #1 / wabil 2026-06-27). // // So when the stored address is NOT already a private LAN // IP, prefer the detected LAN IP — but ONLY when it shares a // /24 with another cluster member (genuine single-LAN). A // multi-DC / public-only node yields None or a non-matching // /24 and falls back to public_ip exactly as before, so an // inter-site link is never wiped. Crucially we leave a real // PRIVATE address untouched (any /24) — a different-site // private node keeps its address so its deliberate behind- // NAT roaming isn't turned into a public endpoint. let addr_is_private_lan = lan_prefix(&node.address).is_some(); let effective_addr = if addr_is_private_lan { node.address.clone() } else { // Pick the local IP whose /24 matches a cluster member, // chosen from ALL local private IPs (sorted) — NOT // detect_lan_ip()'s "first private", which on a Proxmox // host with many bridges lands on a non-cluster // interface and flapped this endpoint between the LAN IP // and the public IP run-to-run (wabil 2026-06-27). networking::local_lan_ips().into_iter() .find(|lan| lan_prefix(lan) .is_some_and(|p| cluster_lan_prefixes.contains(&p))) .or_else(|| node.public_ip.clone()) .unwrap_or_else(|| node.address.clone()) }; infos.push(NodeWnInfo { hostname, wolfnet_ip, public_key, wolfnet_port: listen_port, is_self: true, lan_address: effective_addr, public_ip: node.public_ip.clone(), port: node.port, current_peers: extract_peers(&info), site: node.site.clone(), }); } None => { errors.push(format!("{}: WolfNet not running", node.hostname)); } } } else { // Fetch from remote node — try HTTPS first, then HTTP fallback let urls = build_node_urls(&node.address, node.port, "/api/networking/wolfnet/local-info"); let mut fetched = false; for url in &urls { match client.get(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&state.cluster_secret) .send().await { Ok(resp) => { if let Ok(info) = resp.json::().await { if info.get("error").is_some() { errors.push(format!("{}: {}", node.hostname, info["error"])); fetched = true; break; } let hostname = info["hostname"].as_str().unwrap_or("").to_string(); let wolfnet_ip = info["address"].as_str().unwrap_or("").to_string(); let public_key = info["public_key"].as_str().unwrap_or("").to_string(); let listen_port = info["listen_port"].as_u64().unwrap_or(9600) as u16; if wolfnet_ip.is_empty() || public_key.is_empty() { errors.push(format!("{}: WolfNet not configured", node.hostname)); fetched = true; break; } infos.push(NodeWnInfo { hostname, wolfnet_ip, public_key, wolfnet_port: listen_port, is_self: false, lan_address: node.address.clone(), public_ip: node.public_ip.clone(), port: node.port, current_peers: extract_peers(&info), site: node.site.clone(), }); fetched = true; break; } } Err(_) => continue, // Try next URL } } if !fetched { errors.push(format!("{}: unreachable on all ports/protocols", node.hostname)); } } } if infos.len() < 2 { return HttpResponse::Ok().json(serde_json::json!({ "status": "error", "message": "Could not reach enough nodes to sync", "errors": errors, })); } // Now tell each node about every other node let mut synced = 0u32; let mut skipped = 0u32; let mut pruned = 0u32; for (i, target) in infos.iter().enumerate() { for (j, peer) in infos.iter().enumerate() { if i == j { continue; } // Per-target endpoint selection — see `pick_wolfnet_endpoint` // above. `None` means "roaming-only on this target for this // peer" — we translate that into PeerEndpoint::Clear locally // (and the sentinel `__clear__` over the wire) so the remote // handler actively wipes any stale endpoint rather than // preserving the wrong one. let endpoint_choice: Option = pick_wolfnet_endpoint(target, peer); let endpoint_local = match &endpoint_choice { Some(s) => networking::PeerEndpoint::Set(s.clone()), None => networking::PeerEndpoint::Clear, }; let endpoint_wire: &str = match &endpoint_choice { Some(s) => s.as_str(), None => "__clear__", }; if target.is_self { // Add peer locally match networking::add_wolfnet_peer( &peer.hostname, endpoint_local, &peer.wolfnet_ip, Some(&peer.public_key), ) { Ok(_) => { synced += 1; } Err(e) => { if e.contains("already exists") { skipped += 1; } else { errors.push(format!("local add {}: {}", peer.hostname, e)); } } } } else { // Add peer on remote node — try HTTPS first, then HTTP fallback let urls = build_node_urls(&target.lan_address, target.port, "/api/networking/wolfnet/peers"); let payload = serde_json::json!({ "name": peer.hostname, "endpoint": endpoint_wire, "ip": peer.wolfnet_ip, "public_key": peer.public_key, }); let mut posted = false; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&state.cluster_secret) .header("Content-Type", "application/json") .body(payload.to_string()) .send().await { Ok(resp) => { if let Ok(data) = resp.json::().await { if data.get("error").is_some() { let err = data["error"].as_str().unwrap_or("unknown"); if err.contains("already exists") { skipped += 1; } else { errors.push(format!("{} → {}: {}", target.hostname, peer.hostname, err)); } } else { synced += 1; } } posted = true; break; } Err(_) => continue, // Try next URL } } if !posted { errors.push(format!("{} → {}: unreachable on all ports/protocols", target.hostname, peer.hostname)); } } } } // Prune: remove from every synced node ONLY a peer that is POSITIVELY // FOREIGN — one that matches a node we know to be in a DIFFERENT cluster // (the v24.3.6 cross-cluster-merge cleanup; those foreign nodes are in the // registry under another cluster_name). A peer that matches a member, or // that we can't identify at all, is KEPT. // // The old logic pruned every peer NOT in this sync's member list — so // running Update WolfNet Connections from a node with an incomplete view // deleted valid peers and tore down a working mesh (wabil 2026-06-27: that // is what dropped pm2↔pm3 when the sync ran from a node that didn't know // pm1). A None cluster_name is treated as "not positively foreign" (keep). let sync_cluster = node_ids.iter() .filter_map(|nid| state.cluster.get_node(nid).and_then(|n| n.cluster_name)) .next() .unwrap_or_else(|| "WolfStack".to_string()); let foreign_hosts: Vec = state.cluster.get_all_nodes().into_iter() .filter(|n| n.cluster_name.as_deref() .is_some_and(|c| !crate::agent::cluster_eq(Some(c), Some(&sync_cluster)))) .map(|n| n.hostname) .filter(|h| !h.is_empty()) .collect(); for target in &infos { for (peer_name, _peer_ip) in &target.current_peers { // Keep members AND anything we can't positively call foreign. let is_foreign = foreign_hosts.iter().any(|h| hostnames_same_node(peer_name, h)); if !is_foreign { continue; } if target.is_self { match networking::remove_wolfnet_peer(peer_name) { Ok(_) => { pruned += 1; } Err(e) => { if !e.contains("not found") { errors.push(format!("local prune {}: {}", peer_name, e)); } } } } else { let urls = build_node_urls(&target.lan_address, target.port, "/api/networking/wolfnet/peers"); let payload = serde_json::json!({ "name": peer_name }); let mut acted = false; for url in &urls { match client.delete(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&state.cluster_secret) .header("Content-Type", "application/json") .body(payload.to_string()) .send().await { Ok(resp) => { if let Ok(data) = resp.json::().await { match data.get("error").and_then(|v| v.as_str()) { None => { pruned += 1; } Some(err) if err.contains("not found") => {} Some(err) => { errors.push(format!("{} prune {}: {}", target.hostname, peer_name, err)); } } } acted = true; break; } Err(_) => continue, // Try next URL } } if !acted { errors.push(format!("{} prune {}: unreachable on all ports/protocols", target.hostname, peer_name)); } } } } HttpResponse::Ok().json(serde_json::json!({ "status": "ok", "synced": synced, "skipped": skipped, "pruned": pruned, "nodes_reached": infos.len(), "errors": errors, })) } /// POST /api/cluster/diagnose — manually poll each node and report detailed connectivity info pub async fn cluster_diagnose(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let node_ids = &body.node_ids; let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); let client = &*API_HTTP_CLIENT; let mut results = Vec::new(); for nid in node_ids { let node = match state.cluster.get_node(nid) { Some(n) => n, None => { results.push(serde_json::json!({ "node_id": nid, "hostname": "unknown", "address": "", "port": 0, "is_self": false, "wolfstack_api": { "reachable": false, "error": "Node not found in cluster" }, "wolfnet": { "reachable": false }, "last_seen_ago_secs": null, })); continue; } }; let last_seen_ago = if node.last_seen > 0 { Some(now.saturating_sub(node.last_seen)) } else { None }; if node.is_self { results.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "port": node.port, "is_self": true, "wolfstack_api": { "reachable": true, "url_used": "localhost (self)", "status_code": 200, "latency_ms": 0, "error": null, }, "wolfnet": { "ip": "self", "reachable": true, "latency_ms": 0, }, "last_seen_ago_secs": 0, })); continue; } let urls = build_node_urls(&node.address, node.port, "/api/agent/status"); let mut api_result = serde_json::json!({ "reachable": false, "url_used": null, "status_code": null, "latency_ms": null, "error": "Could not reach node on any port/protocol", }); for url in &urls { let start = std::time::Instant::now(); match client.get(url) .timeout(std::time::Duration::from_secs(15)) .peer_auth(&state.cluster_secret) .send().await { Ok(resp) => { let status = resp.status().as_u16(); let latency = start.elapsed().as_millis() as u64; let body_text = resp.text().await.unwrap_or_default(); // Try to parse as AgentMessage let is_valid = serde_json::from_str::(&body_text) .map(|v| v.get("StatusReport").is_some() || v.get("hostname").is_some()) .unwrap_or(false); if status == 200 && (is_valid || body_text.contains("hostname")) { api_result = serde_json::json!({ "reachable": true, "url_used": url, "status_code": status, "latency_ms": latency, "error": null, }); break; } else { // Got a response but not the expected one let snippet = if body_text.len() > 100 { &body_text[..100] } else { &body_text }; api_result = serde_json::json!({ "reachable": false, "url_used": url, "status_code": status, "latency_ms": latency, "error": format!("HTTP {}: {}", status, snippet.trim()), }); // Don't break — try the other port } } Err(e) => { let latency = start.elapsed().as_millis() as u64; let err_str = format!("{}", e); // Only update if we haven't gotten a better result if api_result.get("status_code").and_then(|v| v.as_u64()).is_none() { api_result = serde_json::json!({ "reachable": false, "url_used": url, "status_code": null, "latency_ms": latency, "error": err_str, }); } } } } // Check WolfNet by asking the node about its OWN overlay — not by // looking it up in the bastion's peer list. The bastion can be in a // different cluster, which made every other-cluster node falsely // show "No peer" even when its WolfNet was perfectly healthy. let wolfnet_result = { let urls = build_node_urls(&node.address, node.port, "/api/networking/wolfnet/local-info"); let mut wn = serde_json::json!({ "ip": serde_json::Value::Null, "reachable": false, "peer_count": serde_json::Value::Null, }); for url in &urls { match client.get(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&state.cluster_secret) .send().await { Ok(resp) => { if let Ok(info) = resp.json::().await { let ip = info.get("address").and_then(|v| v.as_str()).unwrap_or(""); if !ip.is_empty() { let peer_count = info.get("peers") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0); wn = serde_json::json!({ "ip": ip, "reachable": true, "peer_count": peer_count, }); } break; } } Err(_) => continue, } } wn }; results.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "port": node.port, "is_self": false, "wolfstack_api": api_result, "wolfnet": wolfnet_result, "last_seen_ago_secs": last_seen_ago, })); } HttpResponse::Ok().json(serde_json::json!({ "results": results })) } /// GET /api/nodes/{id}/pve/resources — list VMs and containers on a Proxmox node pub async fn get_pve_resources(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let node = match state.cluster.get_node(&id) { Some(n) if n.node_type == "proxmox" => n, Some(_) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a Proxmox node" })), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })), }; let token = node.pve_token.unwrap_or_default(); let pve_name = node.pve_node_name.unwrap_or_default(); let fp = node.pve_fingerprint.as_deref(); let client = crate::proxmox::PveClient::new(&node.address, node.port, &token, fp, &pve_name); match client.list_all_guests().await { Ok(guests) => HttpResponse::Ok().json(guests), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/nodes/{id}/pve/{vmid}/{action} — start/stop/restart a Proxmox guest pub async fn pve_guest_action(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, vmid_str, action) = path.into_inner(); let node = match state.cluster.get_node(&id) { Some(n) if n.node_type == "proxmox" => n, Some(_) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a Proxmox node" })), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })), }; let vmid: u64 = match vmid_str.parse() { Ok(v) => v, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid VMID" })), }; // Validate action if !["start", "stop", "shutdown", "reboot", "suspend", "resume"].contains(&action.as_str()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid action. Use: start, stop, shutdown, reboot, suspend, resume" })); } let token = node.pve_token.unwrap_or_default(); let pve_name = node.pve_node_name.unwrap_or_default(); let fp = node.pve_fingerprint.as_deref(); let client = crate::proxmox::PveClient::new(&node.address, node.port, &token, fp, &pve_name); // Determine guest type by listing all and finding the VMID let guests = client.list_all_guests().await.unwrap_or_default(); let guest_type = guests.iter() .find(|g| g.vmid == vmid) .map(|g| g.guest_type.clone()) .unwrap_or_else(|| "qemu".to_string()); // default to qemu match client.guest_action(vmid, &guest_type, &action).await { Ok(upid) => HttpResponse::Ok().json(serde_json::json!({ "success": true, "upid": upid, "vmid": vmid, "action": action })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/nodes/{id}/pve/test — test Proxmox API connection pub async fn pve_test_connection(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let node = match state.cluster.get_node(&id) { Some(n) if n.node_type == "proxmox" => n, Some(_) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a Proxmox node" })), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Node not found" })), }; let token = node.pve_token.unwrap_or_default(); let pve_name = node.pve_node_name.unwrap_or_default(); let fp = node.pve_fingerprint.as_deref(); let client = crate::proxmox::PveClient::new(&node.address, node.port, &token, fp, &pve_name); match client.test_connection().await { Ok(version) => HttpResponse::Ok().json(serde_json::json!({ "success": true, "version": version, "node_name": pve_name })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Components API ─── /// GET /api/components — status of all components on this node pub async fn get_components(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // web::block: ~35 systemctl/which subprocesses per call. match web::block(installer::get_all_status).await { Ok(status) => HttpResponse::Ok().json(status), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("component status worker failed: {}", e) })), } } /// GET /api/components/{name}/detail — detailed component info with config and logs pub async fn get_component_detail(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let component = match name.to_lowercase().as_str() { "wolfnet" => installer::Component::WolfNet, "wolfproxy" => installer::Component::WolfProxy, "wolfserve" => installer::Component::WolfServe, "wolfdisk" => installer::Component::WolfDisk, "wolfscale" => installer::Component::WolfScale, "mariadb" => installer::Component::MariaDB, "postgresql" => installer::Component::PostgreSQL, "certbot" => installer::Component::Certbot, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unknown component: {}", name) })), }; // Get service status let (installed, running, enabled) = installer::check_service(component.service_name()); // Get config file contents let config_path = component.config_path(); let config_content = config_path.as_deref() .and_then(|path| std::fs::read_to_string(path).ok()); // Get recent journal logs let logs = get_service_logs(component.service_name(), 50); // Get systemd unit info let unit_info = get_unit_info(component.service_name()); HttpResponse::Ok().json(serde_json::json!({ "name": component.name(), "service": component.service_name(), "description": component.description(), "installed": installed, "running": running, "enabled": enabled, "config_path": config_path, "config": config_content, // Identity only — the password is fetched separately, on an explicit // operator action, so it never rides along in a page load. "credentials": installer::load_credentials(component).map(|c| serde_json::json!({ "username": c.username, "host": c.host, "port": c.port, })), "logs": logs, "unit_info": unit_info, })) } /// GET /api/components/{name}/credentials — reveal the database account /// WolfStack generated at install time. /// /// Separate from `/detail` deliberately: the password is only sent when an /// operator explicitly asks for it, not on every page render. pub async fn get_component_credentials( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let component = match name.to_lowercase().as_str() { "mariadb" => installer::Component::MariaDB, "postgresql" => installer::Component::PostgreSQL, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "This component has no WolfStack-managed credentials" })), }; match installer::load_credentials(component) { Some(c) => HttpResponse::Ok().json(serde_json::json!({ "username": c.username, "password": c.password, "host": c.host, "port": c.port, })), None => HttpResponse::NotFound().json(serde_json::json!({ "error": format!( "No WolfStack-managed credentials for {} on this node. They are \ created when {} is installed from Components; an engine \ installed by hand keeps whatever accounts it already had.", component.name(), component.name() ) })), } } /// PUT /api/components/{name}/config — save component config #[derive(Deserialize)] pub struct SaveConfigRequest { pub content: String, } pub async fn save_component_config( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let component = match name.to_lowercase().as_str() { "wolfnet" => installer::Component::WolfNet, "wolfproxy" => installer::Component::WolfProxy, "wolfserve" => installer::Component::WolfServe, "wolfdisk" => installer::Component::WolfDisk, "wolfscale" => installer::Component::WolfScale, "mariadb" => installer::Component::MariaDB, "postgresql" => installer::Component::PostgreSQL, "certbot" => installer::Component::Certbot, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unknown component: {}", name) })), }; let config_path = match component.config_path() { Some(p) => p, None => return HttpResponse::BadRequest().json(serde_json::json!({ // Distinguish "this component never has one" from "we could not // find this node's copy" — the second is actionable, and used to // surface as a bare ENOENT from a path that never existed. "error": if !component.has_config_file() { "This component has no config file".to_string() } else { format!( "No {} configuration file found on this node. Install and \ initialise {} here first, then reload this page.", component.name(), component.name() ) } })), }; let content = body.content.clone(); let path_for_write = config_path.clone(); // Blocking file I/O must not run on an async worker (actix-web #941). let write_result = web::block(move || { // WolfStack owns its own components' config directories and may have // to create them on first save. A DB engine's path is discovered from // disk, so its parent always exists — nothing is invented here. if let Some(parent) = std::path::Path::new(&path_for_write).parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&path_for_write, &content) }).await; match write_result { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Config saved. Restart {} to apply changes.", component.service_name()) })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save {}: {}", config_path, e) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save config: {}", e) })), } } /// POST /api/components/{name}/install — install a component pub async fn install_component(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let component = match name.to_lowercase().as_str() { "wolfnet" => installer::Component::WolfNet, "wolfproxy" => installer::Component::WolfProxy, "wolfserve" => installer::Component::WolfServe, "wolfdisk" => installer::Component::WolfDisk, "wolfscale" => installer::Component::WolfScale, "mariadb" => installer::Component::MariaDB, "postgresql" => installer::Component::PostgreSQL, "certbot" => installer::Component::Certbot, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unknown component: {}", name) })), }; // web::block: the install pipes `curl | bash` synchronously and can run // for minutes — inline it blocked an actix worker for the duration // (sync-in-async class; found auditing wabil's WolfDisk install-button // report, 2026-07-04). match web::block(move || installer::install_component(component)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("install worker failed: {}", e) })), } } // ─── Service Control API ─── #[derive(Deserialize)] pub struct ServiceActionRequest { pub action: String, // start, stop, restart } /// POST /api/services/{name}/action — start/stop/restart a service pub async fn service_action( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let service = path.into_inner(); // WolfProxy daemonizes (forks a worker, parent exits), so with a // Type=simple unit systemd loses track of the worker: `systemctl stop` // reports success but the orphan keeps holding :80/:443, and the next // start fails "Address in use" (klasSponsor 2026-06-05). For wolfproxy // stop/restart, reap any orphan still on the host ports after the // systemctl call so the ports are actually freed. Reaping is port-scoped // and name-checked (see installer::wolfproxy_pids_on_ports) so a wolfproxy // inside a container is never touched. if service == "wolfproxy" && (body.action == "stop" || body.action == "restart") { let _ = installer::stop_service("wolfproxy"); let pids = installer::wolfproxy_pids_on_ports(&[80, 443]); let reaped = pids.len(); for pid in &pids { let _ = std::process::Command::new("kill").args(["-TERM", &pid.to_string()]).output(); } if reaped > 0 { tokio::time::sleep(std::time::Duration::from_millis(800)).await; for pid in installer::wolfproxy_pids_on_ports(&[80, 443]) { let _ = std::process::Command::new("kill").args(["-KILL", &pid.to_string()]).output(); } } let note = if reaped > 0 { format!(" (reaped {} orphaned worker{} systemd had lost track of)", reaped, if reaped == 1 { "" } else { "s" }) } else { String::new() }; if body.action == "restart" { // Let the kernel release the listening sockets before re-binding. tokio::time::sleep(std::time::Duration::from_millis(400)).await; return match installer::start_service("wolfproxy") { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("wolfproxy restarted{}", note) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Freed the ports{} but start failed: {}", note, e) })), }; } return HttpResponse::Ok().json(serde_json::json!({ "message": format!("wolfproxy stopped{}", note) })); } // WolfNet on Unraid has no systemd unit — the agent supervises the // daemon, so the Components card's Start/Stop/Restart go to the same // supervisor path the WolfNet page uses (klas, 2026-09-10). if service == "wolfnet" && installer::unraid_tools::is_unraid() { let action = body.action.clone(); return match web::block(move || networking::wolfnet_service_action(&action)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("WolfNet action worker failed: {}", e) })), }; } let result = match body.action.as_str() { "start" => installer::start_service(&service), "stop" => installer::stop_service(&service), "restart" => installer::restart_service(&service), _ => Err(format!("Unknown action: {}", body.action)), }; match result { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Cron Job Management API ─── #[derive(Deserialize)] pub struct CronJobRequest { pub schedule: String, pub command: String, #[serde(default)] pub comment: String, pub index: Option, #[serde(default = "cron_enabled_default")] pub enabled: bool, } fn cron_enabled_default() -> bool { true } #[derive(serde::Serialize)] struct CronEntry { index: usize, schedule: String, command: String, comment: String, human: String, enabled: bool, raw: String, } fn humanize_schedule(schedule: &str) -> String { match schedule.trim() { "@reboot" => "On reboot".to_string(), "@hourly" => "Every hour".to_string(), "@daily" | "@midnight" => "Every day (midnight)".to_string(), "@weekly" => "Every week".to_string(), "@monthly" => "Every month".to_string(), "@yearly" | "@annually" => "Every year".to_string(), s => { let parts: Vec<&str> = s.split_whitespace().collect(); if parts.len() != 5 { return s.to_string(); } let (min, hour, dom, mon, dow) = (parts[0], parts[1], parts[2], parts[3], parts[4]); // Common patterns if s == "* * * * *" { return "Every minute".to_string(); } if min.starts_with("*/") && hour == "*" && dom == "*" && mon == "*" && dow == "*" { let n = &min[2..]; return format!("Every {} minutes", n); } if min != "*" && hour == "*" && dom == "*" && mon == "*" && dow == "*" { return format!("Hourly at :{}", min); } if min != "*" && hour != "*" && dom == "*" && mon == "*" && dow == "*" { return format!("Daily at {}:{}", hour, if min.len() == 1 { format!("0{}", min) } else { min.to_string() }); } if min != "*" && hour != "*" && dom == "*" && mon == "*" && dow != "*" { let day = match dow { "0" | "7" => "Sunday", "1" => "Monday", "2" => "Tuesday", "3" => "Wednesday", "4" => "Thursday", "5" => "Friday", "6" => "Saturday", _ => dow, }; return format!("Every {} at {}:{}", day, hour, if min.len() == 1 { format!("0{}", min) } else { min.to_string() }); } if min != "*" && hour != "*" && dom != "*" && mon == "*" && dow == "*" { return format!("Monthly on day {} at {}:{}", dom, hour, if min.len() == 1 { format!("0{}", min) } else { min.to_string() }); } s.to_string() } } } fn parse_crontab_line(line: &str, index: usize) -> Option { let trimmed = line.trim(); if trimmed.is_empty() { return None; } // Check for disabled entries if let Some(rest) = trimmed.strip_prefix("# DISABLED: ") { if let Some(entry) = parse_cron_expression(rest, index) { return Some(CronEntry { enabled: false, ..entry }); } return None; } // Skip pure comments if trimmed.starts_with('#') { return None; } parse_cron_expression(trimmed, index) } fn parse_cron_expression(line: &str, index: usize) -> Option { let trimmed = line.trim(); // Handle @reboot, @hourly, etc. if trimmed.starts_with('@') { let parts: Vec<&str> = trimmed.splitn(2, char::is_whitespace).collect(); if parts.len() < 2 { return None; } let schedule = parts[0].to_string(); let rest = parts[1].trim(); let (command, comment) = extract_inline_comment(rest); return Some(CronEntry { human: humanize_schedule(&schedule), index, schedule, command, comment, enabled: true, raw: line.to_string(), }); } // Standard 5-field cron let parts: Vec<&str> = trimmed.splitn(6, char::is_whitespace).collect(); if parts.len() < 6 { return None; } let schedule = parts[..5].join(" "); let rest = parts[5].trim(); let (command, comment) = extract_inline_comment(rest); Some(CronEntry { human: humanize_schedule(&schedule), index, schedule, command, comment, enabled: true, raw: line.to_string(), }) } fn extract_inline_comment(s: &str) -> (String, String) { // Look for # comment at end (not inside quotes) if let Some(pos) = s.rfind(" # ") { (s[..pos].trim().to_string(), s[pos+3..].trim().to_string()) } else { (s.trim().to_string(), String::new()) } } fn read_crontab() -> (Vec, String) { let output = std::process::Command::new("crontab") .arg("-l") .output(); match output { Ok(o) if o.status.success() => { let raw = String::from_utf8_lossy(&o.stdout).to_string(); let lines: Vec = raw.lines().map(|l| l.to_string()).collect(); (lines, raw) } _ => (vec![], String::new()), } } fn write_crontab(lines: &[String]) -> Result<(), String> { let content = lines.join("\n") + "\n"; let mut child = std::process::Command::new("crontab") .arg("-") .stdin(std::process::Stdio::piped()) .spawn() .map_err(|e| format!("Failed to spawn crontab: {}", e))?; use std::io::Write; child.stdin.as_mut().unwrap() .write_all(content.as_bytes()) .map_err(|e| format!("Failed to write crontab: {}", e))?; let status = child.wait().map_err(|e| format!("crontab error: {}", e))?; if status.success() { Ok(()) } else { Err("crontab exited with error".to_string()) } } /// GET /api/cron — list cron entries pub async fn cron_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (lines, raw) = read_crontab(); let entries: Vec = lines.iter().enumerate() .filter_map(|(i, line)| parse_crontab_line(line, i)) .collect(); HttpResponse::Ok().json(serde_json::json!({ "entries": entries, "raw": raw })) } /// POST /api/cron — add or edit a cron entry pub async fn cron_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (mut lines, _) = read_crontab(); let comment_suffix = if body.comment.is_empty() { String::new() } else { format!(" # {}", body.comment) }; let new_line = if body.enabled { format!("{} {}{}", body.schedule, body.command, comment_suffix) } else { format!("# DISABLED: {} {}{}", body.schedule, body.command, comment_suffix) }; if let Some(idx) = body.index { if idx < lines.len() { lines[idx] = new_line; } else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Index out of range" })); } } else { lines.push(new_line); } match write_crontab(&lines) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "status": "saved" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/cron/{index} — remove a cron entry by line index pub async fn cron_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let idx = path.into_inner(); let (mut lines, _) = read_crontab(); if idx >= lines.len() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Index out of range" })); } lines.remove(idx); match write_crontab(&lines) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "status": "deleted" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Container Cron Job Management ─── /// Build a Command to exec inside a container (docker or lxc). fn container_exec_cmd(runtime: &str, container: &str, cmd_args: &[&str]) -> std::process::Command { if runtime == "docker" { let mut cmd = std::process::Command::new("docker"); cmd.arg("exec").arg(container); for a in cmd_args { cmd.arg(a); } cmd } else { lxc_exec_cmd(container, cmd_args) } } /// Like `container_exec_cmd`, but always as root inside the container. /// Package managers need root to take their lock and write their log /// (`/var/log/apk.log`, `/var/lib/dpkg/lock`), and `docker exec` without /// `-u` runs as the image's USER — Grafana's uid 472 made every apk /// upgrade fail with "Unable to open log: Permission denied". `pct exec` /// and `lxc-attach` already attach as uid 0, so LXC is unchanged. The /// general /exec endpoint deliberately keeps the image's default user. fn container_exec_cmd_as_root(runtime: &str, container: &str, cmd_args: &[&str]) -> std::process::Command { if runtime == "docker" { let mut cmd = std::process::Command::new("docker"); cmd.arg("exec").arg("-u").arg("0").arg(container); for a in cmd_args { cmd.arg(a); } cmd } else { lxc_exec_cmd(container, cmd_args) } } /// Build a Command with stdin piped for writing into a container. fn container_exec_cmd_stdin(runtime: &str, container: &str, cmd_args: &[&str]) -> std::process::Command { if runtime == "docker" { let mut cmd = std::process::Command::new("docker"); cmd.arg("exec").arg("-i").arg(container); for a in cmd_args { cmd.arg(a); } cmd.stdin(std::process::Stdio::piped()); cmd } else { let mut cmd = lxc_exec_cmd(container, cmd_args); cmd.stdin(std::process::Stdio::piped()); cmd } } fn read_container_crontab(runtime: &str, container: &str) -> (Vec, String) { let output = container_exec_cmd(runtime, container, &["crontab", "-l"]).output(); match output { Ok(o) if o.status.success() => { let raw = String::from_utf8_lossy(&o.stdout).to_string(); let lines: Vec = raw.lines().map(|l| l.to_string()).collect(); (lines, raw) } _ => (vec![], String::new()), } } fn write_container_crontab(runtime: &str, container: &str, lines: &[String]) -> Result<(), String> { let content = lines.join("\n") + "\n"; let mut child = container_exec_cmd_stdin(runtime, container, &["crontab", "-"]) .spawn() .map_err(|e| format!("Failed to spawn crontab in container: {}", e))?; use std::io::Write; child.stdin.as_mut().unwrap() .write_all(content.as_bytes()) .map_err(|e| format!("Failed to write crontab: {}", e))?; let status = child.wait().map_err(|e| format!("crontab error: {}", e))?; if status.success() { Ok(()) } else { Err("crontab in container exited with error".to_string()) } } /// GET /api/containers/{runtime}/{id}/cron — list cron entries inside a container pub async fn container_cron_list(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let (lines, raw) = read_container_crontab(&runtime, &container); let entries: Vec = lines.iter().enumerate() .filter_map(|(i, line)| parse_crontab_line(line, i)) .collect(); HttpResponse::Ok().json(serde_json::json!({ "entries": entries, "raw": raw })) } /// POST /api/containers/{runtime}/{id}/cron — add or edit a cron entry inside a container pub async fn container_cron_save(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let (mut lines, _) = read_container_crontab(&runtime, &container); let comment_suffix = if body.comment.is_empty() { String::new() } else { format!(" # {}", body.comment) }; let new_line = if body.enabled { format!("{} {}{}", body.schedule, body.command, comment_suffix) } else { format!("# DISABLED: {} {}{}", body.schedule, body.command, comment_suffix) }; if let Some(idx) = body.index { if idx < lines.len() { lines[idx] = new_line; } else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Index out of range" })); } } else { lines.push(new_line); } match write_container_crontab(&runtime, &container, &lines) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "status": "saved" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/containers/{runtime}/{id}/cron/{index} — remove a cron entry from a container pub async fn container_cron_delete(req: HttpRequest, state: web::Data, path: web::Path<(String, String, usize)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (runtime, container, idx) = path.into_inner(); let (mut lines, _) = read_container_crontab(&runtime, &container); if idx >= lines.len() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Index out of range" })); } lines.remove(idx); match write_container_crontab(&runtime, &container, &lines) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "status": "deleted" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Container Update Checking ─── /// Detect which package manager is available inside a container. /// Uses `command -v` (POSIX shell built-in) instead of `which` for compatibility /// with minimal containers (e.g. AlmaLinux) that don't ship `which`. fn detect_container_pkg_manager(runtime: &str, container: &str) -> &'static str { for pm in &["apt", "dnf", "yum", "pacman", "apk"] { let check = format!("command -v {} >/dev/null 2>&1 && echo found", pm); let out = container_exec_cmd_as_root(runtime, container, &["sh", "-c", &check]).output(); if let Ok(o) = out { let stdout = String::from_utf8_lossy(&o.stdout); if o.status.success() && stdout.trim() == "found" { return pm; } } } "unknown" } /// Quick update count check for a container (uses cached package data, no refresh). fn quick_container_update_count(runtime: &str, container: &str) -> (String, usize) { let pm = detect_container_pkg_manager(runtime, container); let cmd = match pm { "apt" => "apt list --upgradable 2>/dev/null | grep -v '^Listing' | grep -c .", "dnf" => "dnf check-update --quiet 2>/dev/null | grep -c '^\\S'", "yum" => "yum check-update --quiet 2>/dev/null | grep -c '^\\S'", "pacman" => "pacman -Qu 2>/dev/null | grep -c .", // `apk version` ALWAYS prints an `Installed: Available:` header line, // even with zero upgrades — counting it showed a phantom "1 update" // on every up-to-date Alpine container, and Apply (which correctly // did nothing) could never clear it (JJ, 2026-06-10; verified in a // live alpine:latest container). tail -n +2 drops the header. "apk" => "apk version -l '<' 2>/dev/null | tail -n +2 | grep -c .", _ => return (pm.to_string(), 0), }; let out = container_exec_cmd_as_root(runtime, container, &["sh", "-c", cmd]).output(); let count = out.ok() .map(|o| String::from_utf8_lossy(&o.stdout).trim().parse::().unwrap_or(0)) .unwrap_or(0); (pm.to_string(), count) } /// POST /api/containers/updates/summary — quick update count for all running containers pub async fn container_updates_summary(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // ENTIRE body is blocking: docker_list_all/lxc_list_all shell out, and the // thread::scope below joins one `docker exec` probe per running container. // Running it directly on the actix worker pegged a worker for the whole // enumeration; enough concurrent calls (the periodic poll + the old // reload-on-view-toggle) starved the workers so /api/ping couldn't be // served, tripping the connection-lost banner (Gary KO4BSR 2026-06-10). // web::block moves it to the blocking threadpool so async workers stay // free to answer the heartbeat. (The frontend also no longer re-fires // this on a card/table toggle.) let results_vec: Vec<(String, String, usize)> = web::block(move || { let docker = containers::docker_list_all(); let lxc = containers::lxc_list_all(); let running: Vec<(String, String)> = docker.iter().chain(lxc.iter()) .filter(|c| c.state == "running") .map(|c| (c.runtime.clone(), c.name.clone())) .collect(); std::thread::scope(|s| { let handles: Vec<_> = running.iter().map(|(runtime, name)| { let runtime = runtime.clone(); let name = name.clone(); s.spawn(move || { let (pm, count) = quick_container_update_count(&runtime, &name); (format!("{}:{}", runtime, name), pm, count) }) }).collect(); handles.into_iter().filter_map(|h| h.join().ok()).collect() }) }).await.unwrap_or_else(|e| { // Blocking-pool failure (a panic in the enumeration). Degrade to an // empty map rather than 500 — the UI just shows no update badges — // but log it so a real regression isn't swallowed silently. tracing::warn!("container_updates_summary: enumeration failed: {}", e); Vec::new() }); let mut results = serde_json::Map::new(); for (key, pm, count) in results_vec { results.insert(key, serde_json::json!({ "package_manager": pm, "count": count })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "containers": results })) } /// POST /api/containers/{runtime}/{id}/updates/check — check for updates inside a container pub async fn container_updates_check(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { // Refreshes the package index as root inside the container (apt-get // update, apk update, pacman -Sy) — a write, so the same operator gate // as apply rather than plain require_auth. if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); // Detection plus the index refresh is up to five `exec` probes and a // network-bound package-index download — 10-60s. Blocking pool, not an // actix worker, or a few concurrent checks stall the heartbeat. let result = web::block(move || { let pkg_manager = detect_container_pkg_manager(&runtime, &container); let run = |cmd: &str| -> String { container_exec_cmd_as_root(&runtime, &container, &["sh", "-c", cmd]) .output().ok().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default() }; let output = match pkg_manager { "apt" => { run("apt-get update -qq 2>/dev/null"); run("apt list --upgradable 2>/dev/null | grep -v '^Listing'") } "dnf" => run("dnf check-update --quiet 2>/dev/null"), "yum" => run("yum check-update --quiet 2>/dev/null"), "pacman" => { run("pacman -Sy 2>/dev/null"); run("pacman -Qu 2>/dev/null") } "apk" => { run("apk update 2>/dev/null"); // tail -n +2 drops apk's unconditional `Installed: Available:` // header — without this the modal rendered the header as a // phantom single "update" with blank columns (JJ, 2026-06-10). run("apk version -l '<' 2>/dev/null | tail -n +2") } _ => String::new(), }; (pkg_manager, output) }).await; let (pkg_manager, output) = match result { Ok(r) => r, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("update check task failed: {}", e), })), }; let count = output.lines().filter(|l| !l.trim().is_empty()).count(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "package_manager": pkg_manager, "count": count, "list": output.trim(), })) } /// POST /api/containers/{runtime}/{id}/updates/apply — apply updates inside a container pub async fn container_updates_apply(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { // Runs a package-manager upgrade as root inside the container — // command execution, so the same operator gate as container_exec. if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); // Detection is up to five sequential `exec` probes — blocking pool. let (runtime_d, container_d) = (runtime.clone(), container.clone()); let pkg_manager = match web::block(move || detect_container_pkg_manager(&runtime_d, &container_d)).await { Ok(pm) => pm, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("package manager detection failed: {}", e), })), }; let cmd = match pkg_manager { "apt" => "DEBIAN_FRONTEND=noninteractive apt-get upgrade -y 2>&1", "dnf" => "dnf upgrade -y 2>&1", "yum" => "yum update -y 2>&1", "pacman" => "pacman -Syu --noconfirm 2>&1", "apk" => "apk upgrade 2>&1", _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "No supported package manager found in container" })), }; // Same as the host apply: the in-container upgrade can take minutes, // so run it on the blocking pool, not on an actix-rt worker thread. let runtime_b = runtime.clone(); let container_b = container.clone(); let output = web::block(move || { container_exec_cmd_as_root(&runtime_b, &container_b, &["sh", "-c", cmd]).output() }).await; match output { Ok(Ok(o)) => { let out = String::from_utf8_lossy(&o.stdout).to_string(); let err = String::from_utf8_lossy(&o.stderr).to_string(); let combined = if err.is_empty() { out } else { format!("{}\n{}", out, err) }; if o.status.success() { HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": combined.trim() })) } else { HttpResponse::InternalServerError().json(serde_json::json!({ "error": combined.trim() })) } } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to execute: {}", e) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("apply task failed: {}", e) })), } } /// POST /api/containers/{runtime}/{id}/exec — run a command inside a container pub async fn container_exec(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { // Command execution: operator identity required, and the built-in // default secret is refused outright. See require_operator_auth. if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let cmd = body["command"].as_str().unwrap_or(""); if cmd.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "No command provided"})); } let output = container_exec_cmd(&runtime, &container, &["sh", "-c", cmd]).output(); match output { Ok(o) => { let stdout = String::from_utf8_lossy(&o.stdout).to_string(); let stderr = String::from_utf8_lossy(&o.stderr).to_string(); HttpResponse::Ok().json(serde_json::json!({ "ok": o.status.success(), "exit_code": o.status.code(), "stdout": stdout, "stderr": stderr, })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Failed: {}", e)})), } } // ─── Container Certificates (certbot + Apache/WolfServe inside a container) ─── /// Build the ExecTarget for a `/api/containers/{runtime}/{id}/certs/*` /// route. Same runtime vocabulary as `parse_exec_target` uses for the /// configurator, but sourced from the path instead of query params. fn container_cert_target(runtime: &str, container: &str) -> Result { if container.is_empty() { return Err(HttpResponse::BadRequest().json(serde_json::json!({"error": "container name is required"}))); } match runtime { "docker" => Ok(crate::configurator::ExecTarget::Docker(container.to_string())), "lxc" => Ok(crate::configurator::ExecTarget::Lxc(container.to_string())), other => Err(HttpResponse::BadRequest().json( serde_json::json!({"error": format!("Unsupported runtime: '{}'", other)}) )), } } /// GET /api/containers/{runtime}/{id}/certs/overview — web server /// detection + certbot presence + certs + parsed sites, in one call. pub async fn container_certs_overview(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; // Many exec round-trips into the container — blocking pool, not an // actix worker. match web::block(move || crate::certbot::container::overview(&target)).await { Ok(ov) => HttpResponse::Ok().json(ov), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// POST /api/containers/{runtime}/{id}/certs/install-certbot — install /// certbot via the container's package manager. Software install → /// operator gate, same as updates/apply. pub async fn container_certs_install_certbot(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::certbot::container::install_certbot(&target)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct ContainerCertIssueRequest { pub domains: Vec, #[serde(default)] pub email: String, /// Site config file whose DocumentRoot serves the HTTP-01 webroot; /// the issued cert is attached to it afterwards. pub site: String, } /// POST /api/containers/{runtime}/{id}/certs/issue — issue via webroot /// inside the container, then attach the new cert to the site. The /// attach step is reported separately: the cert exists on disk even if /// the vhost rewrite fails, and the UI must not present a /// half-succeeded issue as a total failure. pub async fn container_certs_issue(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; let reqb = body.into_inner(); let result = web::block(move || { // Resolve the webroot from the site's DocumentRoot — issuance is // always for an already-configured website (that's the flow this // page exists for). let sites = crate::certbot::container::list_sites_with_ssl(&target)?; let site = sites.iter().find(|s| s.name == reqb.site) .ok_or_else(|| format!("site '{}' not found", reqb.site))?; if site.doc_root.is_empty() { return Err(format!( "site '{}' has no DocumentRoot — webroot issuance needs one to serve the \ ACME challenge. Add a DocumentRoot to the vhost first.", reqb.site)); } // Fall back to the host Cert Manager's saved email so the // operator doesn't retype it — same convention as host issue. let email = if reqb.email.trim().is_empty() { crate::certbot::CertbotConfig::load().email } else { reqb.email.trim().to_string() }; let issue_out = crate::certbot::container::issue_in_container( &target, &reqb.domains, &email, &site.doc_root)?; // Locate the lineage certbot just created and attach it. let attach = match crate::certbot::container::find_cert_for_domain(&target, &reqb.domains[0]) { Some(cert) => crate::certbot::container::attach_cert_to_site(&target, &reqb.site, &cert.name), None => Err(format!( "certbot reported success but no certificate for '{}' was found in {} — \ attach it manually once it appears", reqb.domains[0], crate::certbot::LE_LIVE_DIR)), }; Ok::<_, String>((issue_out, attach)) }).await; match result { Ok(Ok((issue_out, attach))) => { let (attached, attach_error) = match &attach { Ok(_) => (true, String::new()), Err(e) => (false, e.clone()), }; HttpResponse::Ok().json(serde_json::json!({ "message": "certificate issued", "output": issue_out.trim(), "attached": attached, "attach_error": attach_error, })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct ContainerCertNameRequest { pub name: String, } /// POST /api/containers/{runtime}/{id}/certs/renew — force-renew one /// cert inside the container and reload its web server. pub async fn container_certs_renew(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; let name = body.name.clone(); match web::block(move || crate::certbot::container::renew_in_container(&target, &name)).await { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({"message": "certificate renewed", "output": out.trim()})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct ContainerCertAttachRequest { pub site: String, pub cert_name: String, } /// POST /api/containers/{runtime}/{id}/certs/attach — point a site's /// vhost at an existing cert (rewrites SSL paths or appends a :443 /// vhost), config-tested with rollback, then reloads. pub async fn container_certs_attach(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; let (site, cert) = (body.site.clone(), body.cert_name.clone()); match web::block(move || crate::certbot::container::attach_cert_to_site(&target, &site, &cert)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// DELETE /api/containers/{runtime}/{id}/certs/{name} — certbot delete /// inside the container (cleans live/, archive/ and the renewal conf). pub async fn container_certs_delete(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (runtime, container, name) = path.into_inner(); let target = match container_cert_target(&runtime, &container) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::certbot::container::delete_in_container(&target, &name)).await { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({"message": "certificate deleted", "output": out.trim()})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } // ─── Certbot API ─── #[derive(Deserialize)] pub struct CertRequest { pub domain: String, pub email: String, } /// POST /api/certificates — request a certificate (legacy HTTP-01 /// standalone path). When port 80 is busy (typical for hosts running /// WolfProxy), we return 409 Conflict with a `port_80_busy: true` /// marker so the frontend can pivot to the DNS-01 + wildcard flow /// without parsing free-form certbot stderr. For new integrations, /// prefer POST /api/certs with `dns_provider_id` set. pub async fn request_certificate(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match installer::request_certificate(&body.domain, &body.email) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => { if let Some(rest) = e.strip_prefix(installer::CERT_PORT80_BUSY_PREFIX) { HttpResponse::Conflict().json(serde_json::json!({ "error": rest, "port_80_busy": true, })) } else { HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })) } } } } /// GET /api/certificates/list — list installed certificates pub async fn list_certificates(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Use the exact same discovery as startup (find_tls_certificate) let certs = installer::list_certificates(); HttpResponse::Ok().json(certs) } #[derive(Deserialize)] pub struct CertInstallRequest { pub cert_pem: String, pub key_pem: String, #[serde(default)] pub cert_path: Option, #[serde(default)] pub key_path: Option, /// Passphrase for an encrypted private key (PKCS#8 ENCRYPTED PRIVATE KEY /// or legacy Proc-Type: ENCRYPTED). Optional — required only when the /// pasted key is passphrase-protected. Stored only as long as it takes /// openssl to decrypt the key, never persisted to disk. #[serde(default)] pub key_passphrase: Option, } /// POST /api/certificates/install — write user-supplied PEM cert+key to disk. /// Used for both fresh installs and replacing/updating existing certs (e.g. /// overwriting the Proxmox pveproxy-ssl pair). /// /// Response includes `restart_service`: the systemd unit the user should /// be prompted to restart for the new cert to take effect (`wolfstack` or /// `pveproxy`). The frontend opens a confirm modal — we never auto-restart. pub async fn install_certificate( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target_cert = body.cert_path.clone().unwrap_or_else(|| "/etc/wolfstack/cert.pem".to_string()); let restart_service = installer::restart_service_name_for_cert(&target_cert); match installer::install_certificate_files( &body.cert_pem, &body.key_pem, body.cert_path.as_deref(), body.key_path.as_deref(), body.key_passphrase.as_deref(), ) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg, "restart_service": restart_service, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct CertSelfSignedRequest { pub host: String, #[serde(default)] pub alt_names: Vec, #[serde(default)] pub cert_path: Option, #[serde(default)] pub key_path: Option, #[serde(default)] pub days: Option, } /// POST /api/certificates/self-signed — generate a self-signed cert via openssl. pub async fn create_self_signed_certificate( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target_cert = body.cert_path.clone().unwrap_or_else(|| "/etc/wolfstack/cert.pem".to_string()); let restart_service = installer::restart_service_name_for_cert(&target_cert); match installer::generate_self_signed_certificate( &body.host, &body.alt_names, body.cert_path.as_deref(), body.key_path.as_deref(), body.days.unwrap_or(825), ) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg, "restart_service": restart_service, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct CertRestartRequest { pub service: String, } /// POST /api/certificates/restart-service — explicitly restart wolfstack /// or pveproxy after a cert install. Called by the frontend's confirm /// modal so the user controls the restart timing. Validated against a /// fixed allowlist; arbitrary services are rejected. pub async fn cert_restart_service( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match installer::restart_cert_service(&body.service) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── Local Certificate Authority (internal-domain certs) ───────────── // For domains that can't use public ACME (*.ai.home, *.lab.lan …): // generate one root CA, install it once per device, then issue // CA-signed leaf certs that are trusted automatically. Pairs with the // WolfRouter wildcard-DNS + proxy editor for an all-in-one local stack. /// A leaf cert/key path is only safe if it has no `..` traversal segment — /// the file write runs as root, so an unvalidated path could clobber any /// file on the box. fn local_ca_path_is_safe(p: &str) -> bool { !p.split(['/', '\\']).any(|seg| seg == "..") } /// GET /api/certificates/local-ca — does the local CA exist + basic info. pub async fn local_ca_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let info = web::block(|| { use openssl::nid::Nid; let exists = crate::local_ca::ca_exists(); let mut info = serde_json::json!({ "exists": exists, "cert_path": crate::local_ca::ca_cert_path() }); if exists && let Ok(pem) = crate::local_ca::ca_cert_pem() && let Ok(cert) = openssl::x509::X509::from_pem(&pem) { let cn = cert.subject_name().entries_by_nid(Nid::COMMONNAME).next() .and_then(|e| e.data().to_string().ok()) .unwrap_or_default(); info["subject"] = serde_json::json!(cn); info["not_after"] = serde_json::json!(cert.not_after().to_string()); } info }).await.unwrap_or_else(|_| serde_json::json!({ "exists": false })); HttpResponse::Ok().json(info) } #[derive(Deserialize)] pub struct LocalCaInitRequest { #[serde(default)] pub label: Option } /// POST /api/certificates/local-ca/init — generate the root CA (idempotent; /// a no-op if it already exists). 4096-bit RSA, so off the runtime. pub async fn local_ca_init(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let label = body.label.clone().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "WolfStack".to_string()); match web::block(move || crate::local_ca::ensure_ca(&label)).await { Ok(Ok(_)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "cert_path": crate::local_ca::ca_cert_path(), "message": "Local CA ready. Download the CA certificate and install it in your devices' trust stores so every issued cert is trusted automatically." })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("ca gen task: {}", e) })), } } /// GET /api/certificates/local-ca/download — the root CA cert for trust-store /// install. Public half only; the CA private key never leaves the host. pub async fn local_ca_download(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match web::block(crate::local_ca::ca_cert_pem).await { Ok(Ok(pem)) => HttpResponse::Ok() .insert_header(("Content-Type", "application/x-pem-file")) .insert_header(("Content-Disposition", "attachment; filename=\"wolfstack-local-ca.pem\"")) .body(pem), Ok(Err(e)) => { tracing::warn!("local CA download: {}", e); HttpResponse::NotFound().json(serde_json::json!({ "error": "Local CA not initialised yet — run init first" })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct LocalCaIssueRequest { pub domain: String, #[serde(default)] pub cert_path: Option, #[serde(default)] pub key_path: Option, } /// POST /api/certificates/local-ca/issue — issue a leaf cert for `domain` /// (SAN covers `domain` + `*.domain`) signed by the local CA, written to /// disk. Auto-creates the CA if absent. Returns the cert/key paths to /// reference in the WolfRouter proxy editor's ssl_certificate fields. pub async fn local_ca_issue(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let domain = body.domain.trim().trim_start_matches("*.").trim_start_matches('.').to_string(); if domain.is_empty() || domain.contains('/') || domain.contains('#') || domain.chars().any(|c| c.is_whitespace()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "domain must be a bare domain like ai.home (no slashes, '#', or spaces)" })); } let safe = domain.replace(|c: char| !c.is_alphanumeric() && c != '.' && c != '-', "_"); let cert_path = body.cert_path.clone().filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| format!("{}/issued/{}.crt", crate::local_ca::ca_dir(), safe)); let key_path = body.key_path.clone().filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| format!("{}/issued/{}.key", crate::local_ca::ca_dir(), safe)); // Operator-supplied paths are written as root — reject traversal. if !local_ca_path_is_safe(&cert_path) || !local_ca_path_is_safe(&key_path) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "cert_path / key_path must not contain '..'" })); } let (d, cp, kp) = (domain.clone(), cert_path.clone(), key_path.clone()); let res = web::block(move || -> Result<(), String> { crate::local_ca::ensure_ca("WolfStack")?; let (cert_pem, key_pem) = crate::local_ca::issue_leaf(&d, &[])?; if let Some(parent) = std::path::Path::new(&cp).parent() { std::fs::create_dir_all(parent).map_err(|e| format!("mkdir: {}", e))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); } } crate::local_ca::write_secret_file(&kp, &key_pem)?; // 0600, no umask race std::fs::write(&cp, &cert_pem).map_err(|e| format!("write cert: {}", e))?; Ok(()) }).await; match res { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "domain": domain, "cert_path": cert_path, "key_path": key_path, "message": format!("Issued a CA-signed cert for {0} and *.{0}. Point your proxy vhost's ssl_certificate / ssl_certificate_key at these paths.", domain) })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("issue task: {}", e) })), } } #[derive(Deserialize)] pub struct LocalPublishRequest { pub domain: String, pub backend: String, } /// POST /api/local-publish — one action: issue a local-CA cert for `domain` /// AND create a managed reverse-proxy vhost (HTTPS, websocket-ready, /// HTTP→HTTPS redirect) for it pointing at `backend`. With a /// `*. → this host` wildcard-DNS entry, the result is a trusted /// internal service at https:// — the all-in-one local stack. /// Targets the local host's managed proxy. pub async fn local_publish(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let domain = body.domain.trim().trim_start_matches("*.").trim_start_matches('.').to_string(); if domain.is_empty() || domain.contains('/') || domain.contains('#') || domain.chars().any(|c| c.is_whitespace()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "domain must be a bare domain like sonarr.ai.home (no slashes, '#', or spaces)" })); } // Default to http:// when no scheme is given — apps speak plain HTTP behind the proxy. let raw = body.backend.trim(); let backend = if raw.contains("://") { raw.to_string() } else { format!("http://{}", raw) }; // Strict allowlist — `backend` is interpolated into nginx `proxy_pass`, // so a stray `;` `{` `}` or space could inject or break the config. let backend_ok = !backend.is_empty() && backend.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':' | '/')); if !backend_ok { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "backend must be host:port or http(s)://host:port (letters, digits, . - _ : / only)" })); } let safe = domain.replace(|c: char| !c.is_alphanumeric() && c != '.' && c != '-', "_"); let cert_path = format!("{}/issued/{}.crt", crate::local_ca::ca_dir(), safe); let key_path = format!("{}/issued/{}.key", crate::local_ca::ca_dir(), safe); let (d, bp, cp, kp, dom) = (domain.clone(), backend.clone(), cert_path.clone(), key_path.clone(), domain.clone()); let res = web::block(move || -> Result { use crate::configurator::{nginx, ExecTarget}; crate::local_ca::ensure_ca("WolfStack")?; let (cert_pem, key_pem) = crate::local_ca::issue_leaf(&d, &[])?; if let Some(parent) = std::path::Path::new(&cp).parent() { std::fs::create_dir_all(parent).map_err(|e| format!("mkdir: {}", e))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); } } crate::local_ca::write_secret_file(&kp, &key_pem)?; // 0600, no umask race std::fs::write(&cp, &cert_pem).map_err(|e| format!("write cert: {}", e))?; let params = nginx::NginxSiteParams { server_name: dom.clone(), listen_port: 443, ssl: true, ssl_cert: Some(cp.clone()), ssl_key: Some(kp.clone()), proxy_pass: Some(bp.clone()), root: None, }; let cfg = nginx::generate_site_config(¶ms); let target = ExecTarget::Host; // Write → enable → reload so the vhost is actually LIVE (save_site // alone only writes the file). enable_site is a no-op where sites // are served directly; reload validates + activates and surfaces a // bad config as an error instead of a false "Live" claim. nginx::save_site(&target, &dom, &cfg)?; let _ = nginx::enable_site(&target, &dom); nginx::reload(&target).map_err(|e| format!("proxy reload failed (cert + vhost written, but not active): {}", e))?; Ok("vhost saved, enabled and proxy reloaded".to_string()) }).await; match res { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "domain": domain, "backend": backend, "url": format!("https://{}", domain), "cert_path": cert_path, "message": format!("Published https://{} → {} ({}). Existing vhost for this domain is replaced.", domain, backend, msg) })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("publish task: {}", e) })), } } // ─── Agent API (server-to-server, no auth required) ─── /// GET /api/agent/status — return this node's status (for remote polling) /// Uses pre-cached data from the self-monitor loop (2s manager / 5s agent) for instant responses. pub async fn agent_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } // Return cached status if available (sub-millisecond response) if let Ok(cache) = state.cached_status.read() && let Some(ref json) = *cache { return HttpResponse::Ok().json(json); } // Cache miss. Do NOT collect here. // // This used to fall through to its own full collection — sysinfo, // docker, lxc and VM enumeration — on a blocking thread, taking // `monitor`'s mutex on the way. Harmless for the single startup request // it was written for; catastrophic at a cluster's poll rate. // // On a node with peers, EVERY poll arriving before the cache was first // populated took that path at once. Each consumed a blocking-pool // thread and queued on the same mutex. The pool caps at 512 and tokio's // blocking queue is unbounded (runtime/blocking/pool.rs — at the cap it // simply pushes and returns), so the background refresher's own // spawn_blocking queued behind the stampede it had caused, and could // never publish the cache that would have ended it. Requests stopped // returning, so actix never closed their connections, and inbound // CLOSE-WAIT grew without limit until the descriptor table was gone. // Observed on a user's cluster 2026-08-13: ~320 leaked sockets/second, // reproducible within seconds of every restart, never self-healing. // // 503 is the honest answer: this node cannot report yet. The cluster // poller already treats non-2xx as an unsuccessful poll and drains the // body (enforced by tests/resource_safety.rs), so a peer neither hangs // nor records stale data. The refresher publishes on its first tick, // which now runs at startup rather than one interval later. HttpResponse::ServiceUnavailable() .insert_header(("Retry-After", "1")) .json(serde_json::json!({ "error": "status cache warming up", "node_id": state.cluster.self_id.clone(), })) } /// POST /api/install/{tech} — install Docker, LXC, or KVM on this node pub async fn install_runtime( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let tech = path.into_inner().to_lowercase(); // Detect distro for package manager let distro = installer::detect_distro(); let (pm, install_flag) = installer::pkg_install_cmd(distro); let packages = match tech.as_str() { "docker" => { // Use Docker's install script for best compatibility let result = std::process::Command::new("bash") .args(["-c", "curl -fsSL https://get.docker.com | sh"]) .output(); match result { Ok(o) if o.status.success() => { // Enable and start Docker let _ = std::process::Command::new("systemctl").args(["enable", "--now", "docker"]).output(); return HttpResponse::Ok().json(serde_json::json!({ "message": "Docker installed and started successfully" })); } Ok(o) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Docker install failed: {}", String::from_utf8_lossy(&o.stderr)) })); } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to run Docker installer: {}", e) })); } } } "lxc" => match distro { installer::DistroFamily::Debian => "lxc lxc-templates", installer::DistroFamily::RedHat => "lxc lxc-templates lxc-extra", installer::DistroFamily::Suse => "lxc", installer::DistroFamily::Arch => "lxc", _ => "lxc", }, "kvm" => match distro { installer::DistroFamily::Debian => "qemu-system-x86 qemu-utils libvirt-daemon-system virtinst ovmf", installer::DistroFamily::RedHat => "qemu-kvm libvirt virt-install", installer::DistroFamily::Suse => "qemu-kvm libvirt virt-install", installer::DistroFamily::Arch => "qemu-full libvirt virt-install edk2-ovmf", _ => "qemu-system-x86", }, _ => { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unknown technology: {}. Use docker, lxc, or kvm.", tech) })); } }; // Run package install let cmd = format!("{} {} {}", pm, install_flag, packages); let result = std::process::Command::new("bash") .args(["-c", &cmd]) .output(); match result { Ok(o) if o.status.success() => { // Post-install actions if tech == "lxc" { containers::ensure_lxc_bridge(); } else if tech == "kvm" { let _ = std::process::Command::new("systemctl").args(["enable", "--now", "libvirtd"]).output(); } HttpResponse::Ok().json(serde_json::json!({ "message": format!("{} installed successfully", tech) })) } Ok(o) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Install failed: {}", String::from_utf8_lossy(&o.stderr)) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to run installer: {}", e) })), } } /// GET /api/geolocate?ip={address} — server-side geolocation proxy /// Proxies requests to ip-api.com because their free tier is HTTP-only, /// and browsers block HTTP requests from HTTPS pages (mixed content). /// Also resolves domain names to IPs before lookup. pub async fn geolocate(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let ip_or_host = match query.get("ip") { Some(v) if !v.is_empty() => v.clone(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing ip parameter" })), }; // If it's a domain name (not an IP), resolve it to an IP first let ip = if ip_or_host.parse::().is_ok() { ip_or_host } else { // DNS lookup match tokio::net::lookup_host(format!("{}:0", ip_or_host)).await { Ok(mut addrs) => { if let Some(addr) = addrs.next() { addr.ip().to_string() } else { return HttpResponse::Ok().json(serde_json::json!({ "status": "fail", "message": "DNS resolution returned no addresses", "query": ip_or_host })); } } Err(e) => { return HttpResponse::Ok().json(serde_json::json!({ "status": "fail", "message": format!("DNS resolution failed: {}", e), "query": ip_or_host })); } } }; // Call ip-api.com server-side (HTTP is fine from backend) let url = format!("http://ip-api.com/json/{}", ip); let client = &*API_HTTP_CLIENT; match client.get(&url).timeout(std::time::Duration::from_secs(5)).send().await { Ok(resp) => { match resp.json::().await { Ok(data) => HttpResponse::Ok().json(data), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "status": "fail", "message": format!("Failed to parse response: {}", e), "query": ip })), } } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "status": "fail", "message": format!("Request failed: {}", e), "query": ip })), } } /// GET /api/traceroute?target= /// /// Runs `traceroute -n -w 1 -q 1 -m 20 ` and returns the parsed /// hops as JSON. Used by WolfRouter's Visual TraceRoute tab to draw the /// internet path on a map (each hop's IP is then geolocated client-side /// via the existing /api/geolocate proxy). /// /// Returns: { target, resolved_ip, hops: [{hop, ip, rtt_ms}, ...] } /// Hops with `ip == null` are timeouts (rendered as "* * *" by traceroute). pub async fn traceroute_handler( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match query.get("target") { Some(v) if !v.trim().is_empty() => v.trim().to_string(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing target parameter (IP or hostname)" })), }; // Validate the target — only allow chars that can appear in a host // or IP. Stops shell-injection via the target arg even though we // pass it as an argv element (defence in depth). let valid = !target.is_empty() && target.len() <= 253 && target.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == ':'); if !valid { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid target — only alphanumeric, dot, dash, and colon are allowed" })); } // Resolve to an IP up front (so the response carries it for the // map's destination marker). We still pass the original target to // traceroute so the user sees the same hostname in their result. let resolved_ip = match tokio::net::lookup_host(format!("{}:0", target)).await { Ok(mut addrs) => addrs.next().map(|a| a.ip().to_string()).unwrap_or_default(), Err(_) => String::new(), }; // -n: numeric output (skip reverse DNS, much faster) // -w 1: 1s wait per probe // -q 1: one query per hop (default 3 — slows things down) // -m 20: 20-hop max (most paths are <15) let target_for_cmd = target.clone(); let output = tokio::task::spawn_blocking(move || { std::process::Command::new("traceroute") .args(["-n", "-w", "1", "-q", "1", "-m", "20", &target_for_cmd]) .output() }).await; let output = match output { Ok(Ok(o)) => o, Ok(Err(e)) => { // Distinguish "traceroute isn't installed" from any other // spawn failure — the frontend uses `missing_tool` to show // an inline install button instead of a generic error. // Adam Cogswell 2026-04-30: Ubuntu minimal images ship // without traceroute and the previous error gave the user // no in-app remedy. let is_missing = e.kind() == std::io::ErrorKind::NotFound || e.raw_os_error() == Some(2 /* ENOENT */); // Manual-install command for THIS host's distro. None when // we can't identify the distro — better than guessing // `apt-get` on Gentoo/Alpine/etc., which would mislead the // user. The frontend renders a generic "install with your // package manager" message in that case. let install_command = if is_missing { let distro = crate::installer::detect_distro(); if matches!(distro, crate::installer::DistroFamily::Unknown) { None } else { let (mgr, args) = crate::installer::pkg_install_cmd(distro); Some(format!("sudo {} {} traceroute", mgr, args)) } } else { None }; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": if is_missing { "traceroute isn't installed on this host. Click the button below to install it, or run the install manually.".to_string() } else { format!("Failed to run traceroute: {}", e) }, "missing_tool": if is_missing { Some("traceroute") } else { None }, "install_package": if is_missing { Some("traceroute") } else { None }, "install_command": install_command, })); } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("traceroute task panicked: {}", e), })); } }; // traceroute prints the header line "traceroute to ..." then one // line per hop. Numeric (-n) format: // 1 192.168.1.1 0.500 ms // 2 10.0.0.1 5.234 ms // 3 * let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); let mut hops: Vec = Vec::new(); for line in stdout.lines() { let trimmed = line.trim_start(); // Skip header if trimmed.starts_with("traceroute") || trimmed.is_empty() { continue; } let mut fields = trimmed.split_whitespace(); let hop_num: u32 = match fields.next().and_then(|s| s.parse().ok()) { Some(n) => n, None => continue, }; // Next field is either an IP or "*" let second = fields.next().unwrap_or(""); if second == "*" { hops.push(serde_json::json!({ "hop": hop_num, "ip": null, "rtt_ms": null, })); continue; } // Validate it really looks like an IP — anything else is a // weird traceroute quirk, skip the line rather than misrender. let ip_ok = second.parse::().is_ok(); if !ip_ok { continue; } // Find the rtt — last numeric token before "ms". let mut rtt_ms: Option = None; let tokens: Vec<&str> = trimmed.split_whitespace().collect(); for window in tokens.windows(2) { if window[1] == "ms" && let Ok(v) = window[0].parse::() { rtt_ms = Some(v); break; } } hops.push(serde_json::json!({ "hop": hop_num, "ip": second, "rtt_ms": rtt_ms, })); } if hops.is_empty() && !output.status.success() { return HttpResponse::Ok().json(serde_json::json!({ "target": target, "resolved_ip": resolved_ip, "hops": [], "error": format!("traceroute failed: {}", stderr.trim()), })); } HttpResponse::Ok().json(serde_json::json!({ "target": target, "resolved_ip": resolved_ip, "hops": hops, })) } /// GET/POST /api/nodes/{id}/proxy/{path:.*} — proxy API calls to a remote node pub async fn node_proxy( req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Bytes, ) -> HttpResponse { // Capture WHO is proxying. Endpoints that execute commands // (require_operator_auth) accept a peer's cluster secret only when // it carries this attribution, so a bare node-to-node call cannot // reach a shell. Deliberately NOT stamped when our own caller was // itself a peer ("cluster-node"): otherwise a secret-holder could // chain through any node's proxy to manufacture operator identity. let actor = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let actor_read_only = session_is_read_only(&req, &state); let (node_id, api_path) = path.into_inner(); // Find the node let node = match state.cluster.get_node(&node_id) { Some(n) => n, None => return HttpResponse::NotFound().json(serde_json::json!({"error": "Node not found"})), }; // If it's the local node, tell frontend to use local API if node.is_self { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Use local API for self node"})); } let method = req.method().clone(); let content_type = req.headers().get("content-type").and_then(|ct| ct.to_str().ok()).unwrap_or("application/json").to_string(); let body_vec = body.to_vec(); let qs = req.query_string(); let query_suffix = if qs.is_empty() { String::new() } else { format!("?{}", qs) }; let path_with_query = format!("/api/{}{}", api_path, query_suffix); let urls = build_node_urls(&node.address, node.port, &path_with_query); // reqwest's timeout covers the WHOLE response, body included, so a // streamed job (Server-Sent Events: a Galera build, a mail install) would // be cut off mid-log at 300 s while the job carried on unseen. A caller // that asks for an event stream gets a long but still bounded ceiling, so // a hung peer can never pin the connection forever. let wants_stream = req.headers().get("accept") .and_then(|v| v.to_str().ok()) .map(|v| v.contains("text/event-stream")) .unwrap_or(false); let timeout_secs = if wants_stream { 4 * 3600 } else if method == actix_web::http::Method::POST || method == actix_web::http::Method::PUT { 300 } else { 120 }; // Use the shared client (accepts self-signed certs, connect_timeout 3s) let client = &*API_HTTP_CLIENT; let mut last_error = String::new(); for url in &urls { let mut builder = match method { actix_web::http::Method::GET => client.get(url), actix_web::http::Method::POST => client.post(url), actix_web::http::Method::PUT => client.put(url), actix_web::http::Method::DELETE => client.delete(url), actix_web::http::Method::PATCH => client.patch(url), _ => client.get(url), }; builder = builder.timeout(std::time::Duration::from_secs(timeout_secs)); builder = builder.header("content-type", &content_type); builder = builder.peer_auth(state.cluster_secret.clone()); // Mark this as a proxied OPERATOR action (a real user request forwarded // on their behalf), distinct from a node-to-node propagation. The target // node authenticates both via the fleet secret, so handlers that must // treat "an operator edited via /api/nodes/{id}/proxy" differently from // "a peer synced state to me" (e.g. image_watcher_config_save) key off // this stamp. Handlers that don't care simply ignore it. builder = builder.header("X-WolfStack-Proxied", "1"); // Operator attribution for command-execution endpoints on the // far side. Omitted when the caller was another peer, which // makes those endpoints refuse the forwarded call. if actor != "cluster-node" { builder = builder.header("X-WolfStack-Actor", actor.clone()); } // require_auth above already refused a read-only session any // unsafe method. GET-reached sinks on the far node (console // WebSockets, VNC tickets) need to know too — its // require_operator_auth refuses on this header. if actor_read_only { builder = builder.header(PROXIED_ACTOR_ROLE_HEADER, "read-only"); } else if actor != "cluster-node" && crate::auth::session_user_is_admin(&actor) { // Admin-only handlers on the far node can't see this session; // see caller_is_admin. builder = builder.header(PROXIED_ACTOR_ROLE_HEADER, "admin"); } if !body_vec.is_empty() { builder = builder.body(body_vec.clone()); } match builder.send().await { Ok(resp) => { let status = resp.status().as_u16(); let resp_ct = resp.headers().get("content-type") .and_then(|v| v.to_str().ok()) .unwrap_or("application/json") .to_string(); // Stream SSE responses through without buffering if resp_ct.contains("text/event-stream") { use futures::StreamExt; let byte_stream = resp.bytes_stream().map(|chunk| -> Result { match chunk { Ok(b) => Ok(actix_web::web::Bytes::copy_from_slice(&b)), Err(e) => Err(actix_web::error::ErrorBadGateway(e.to_string())), } }); return HttpResponse::build(actix_web::http::StatusCode::from_u16(status).unwrap_or(actix_web::http::StatusCode::OK)) .insert_header(("Content-Type", "text/event-stream")) // identity so the Compress middleware skips this forwarded // SSE stream (gzip would buffer it and stall live output). .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(byte_stream); } // Carry the remote's Content-Disposition through. Without it a // file-manager download from a remote node was saved as // "download" — the browser falls back to the last URL segment // of /api/nodes/{id}/proxy/files/download. // (as raw bytes: reqwest and actix-web use different `http` crates) let resp_cd = resp.headers() .get("content-disposition") .and_then(|v| actix_web::http::header::HeaderValue::from_bytes(v.as_bytes()).ok()); match resp.bytes().await { Ok(bytes) => { let mut out = HttpResponse::build(actix_web::http::StatusCode::from_u16(status).unwrap_or(actix_web::http::StatusCode::OK)); out.content_type(resp_ct); if let Some(cd) = resp_cd { out.insert_header((actix_web::http::header::CONTENT_DISPOSITION, cd)); } return out.body(bytes.to_vec()); } Err(e) => { last_error = format!("Read error from {}: {}", url, e); } } } Err(e) => { last_error = format!("{}: {}", url, e); // Try next URL continue; } } } // All URLs failed HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("Could not reach node {} ({}:{}) — last error: {}", node.hostname, node.address, node.port, last_error) })) } // ─── Helpers ─── /// Get recent journal logs for a service fn get_service_logs(service: &str, lines: u32) -> Vec { Command::new("journalctl") .args(["-u", service, "--no-pager", "-n", &lines.to_string(), "--output", "short-iso"]) .output() .ok() .map(|o| { String::from_utf8_lossy(&o.stdout) .lines() .map(|l| l.to_string()) .collect() }) .unwrap_or_default() } /// Get systemd unit info fn get_unit_info(service: &str) -> serde_json::Value { let get_prop = |prop: &str| -> String { Command::new("systemctl") .args(["show", service, "-p", prop, "--value"]) .output() .ok() .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) .unwrap_or_default() }; serde_json::json!({ "active_state": get_prop("ActiveState"), "sub_state": get_prop("SubState"), "load_state": get_prop("LoadState"), "main_pid": get_prop("MainPID"), "memory_current": get_prop("MemoryCurrent"), "cpu_usage": get_prop("CPUUsageNSec"), "restart_count": get_prop("NRestarts"), "active_enter": get_prop("ActiveEnterTimestamp"), "description": get_prop("Description"), }) } // ─── Containers API ─── /// GET /api/containers/status — get Docker and LXC runtime status /// Common web ports to probe on an LXC container's own IP, most-likely first. /// LXC has no published-port table to read, so we scan these directly. const LXC_WEB_PROBE_PORTS: &[u16] = &[80, 8080, 443, 3000, 8000, 8096, 9000, 5000, 8443, 8123]; /// One open-in-browser candidate: where the backend probes it, and where the /// browser should open it. `open_host = None` means "use the node host the /// dashboard is already on" (Docker host-published ports); `Some(ip)` means /// open that address directly (an LXC container's IP). struct WebCandidate { probe_host: String, probe_port: u16, open_host: Option, open_port: u16, } /// Build the ordered list of open-in-browser candidates for a container. /// App Store first: an app's declared/inferred web port is moved to the front /// so it's probed before anything else. Sync (reads the cached container list) /// — run under web::block. fn build_web_candidates(runtime: &str, name: &str) -> Vec { let mut out: Vec = Vec::new(); let loopback = |ip: &str| ip == "127.0.0.1" || ip == "::1" || ip == "localhost"; let wildcard = |ip: &str| ip == "0.0.0.0" || ip == "::" || ip.is_empty(); match runtime { "docker" => { let Some(c) = containers::docker_list_all_cached().into_iter().find(|c| c.name == name) else { return out; }; // Published TCP ports reachable from a browser (wildcard or a host // IP — not loopback-only). for m in c.port_mappings.iter().filter(|m| { m.published && m.proto.eq_ignore_ascii_case("tcp") && !loopback(&m.host_ip) }) { let (probe_host, open_host) = if wildcard(&m.host_ip) { ("127.0.0.1".to_string(), None) } else { (m.host_ip.clone(), Some(m.host_ip.clone())) }; out.push(WebCandidate { probe_host, probe_port: m.host_port, open_host, open_port: m.host_port }); } // App Store first: float the app's known web port to the front. if let Some(web_cport) = crate::appstore::web_container_port_for(name) && let Some(hp) = c.port_mappings.iter() .find(|m| m.container_port == web_cport && m.published) .map(|m| m.host_port) && let Some(pos) = out.iter().position(|w| w.open_port == hp) { let pick = out.remove(pos); out.insert(0, pick); } } "lxc" => { let Some(c) = containers::lxc_list_all_cached().into_iter().find(|c| c.name == name) else { return out; }; let ip = c.ip_address.trim(); if ip.is_empty() || ip == "-" { return out; } for &p in LXC_WEB_PROBE_PORTS { out.push(WebCandidate { probe_host: ip.to_string(), probe_port: p, open_host: Some(ip.to_string()), open_port: p }); } } _ => {} } out } /// True if `host:port` answers HTTP at all (any status). A bare TCP service /// with no HTTP (a database, etc.) makes reqwest error, so it returns false — /// that's how "no web UI ⇒ no icon" is enforced. async fn web_candidate_responds(host: &str, port: u16) -> bool { let url = format!("http://{}:{}/", host, port); // 700ms was too tight and hid working apps. RutgerDiehard's // speedtest-tracker answers with a normal 302 to its setup wizard, but a // cold PHP/Laravel boot does not manage it inside 700ms — so the container // had no "Open in browser" button despite serving perfectly // (2026-08-07). Anything that has to warm an interpreter, open a database // or run migrations on first hit is in the same position. // // Two attempts: the first pays any cold-start cost and warms the app, the // second then answers quickly. A container with NO web UI still fails fast // — the connection is refused rather than timing out — so this does not // slow down the common case of a database container. for timeout_ms in [2_500u64, 4_000] { let ok = API_HTTP_CLIENT .get(&url) .timeout(std::time::Duration::from_millis(timeout_ms)) .send() .await .is_ok(); if ok { return true; } } false } /// GET /api/containers/{runtime}/{id}/web-url — resolve an "open in browser" /// target for a container, or null if it has no web UI. App Store port first, /// then an HTTP probe of the live candidates; only a port that actually answers /// HTTP is returned. Runs on the node hosting the container (remote nodes via /// the existing proxy route), so probes are node-local. pub async fn container_web_url( req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (runtime, name) = path.into_inner(); if runtime != "docker" && runtime != "lxc" { return HttpResponse::Ok().json(serde_json::json!({ "open_host": null, "open_port": null })); } let (r, n) = (runtime.clone(), name.clone()); let candidates = web::block(move || build_web_candidates(&r, &n)).await.unwrap_or_default(); for cand in candidates { if web_candidate_responds(&cand.probe_host, cand.probe_port).await { return HttpResponse::Ok().json(serde_json::json!({ "open_host": cand.open_host, "open_port": cand.open_port, })); } } HttpResponse::Ok().json(serde_json::json!({ "open_host": null, "open_port": null })) } pub async fn container_runtime_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // docker_status()/lxc_status() probe the runtimes via subprocess — offload so // they don't block an async request worker during the page-load burst. match web::block(|| { serde_json::json!({ "docker": containers::docker_status(), "lxc": containers::lxc_status(), }) }).await { Ok(body) => HttpResponse::Ok().json(body), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "runtime status unavailable"})), } } /// GET /api/containers/docker — list all Docker containers pub async fn docker_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // `docker_list_all_cached` runs `docker ps`/inspect subprocesses on a cache // miss. Running that directly in the async handler blocked an actix request // worker; under the page-load burst that starved the worker pool and the // list came up blank for 10-20s (KO4BSR/wabil). Offload to the blocking pool. // This is a human looking at the container list, so it is the one caller // allowed to pay for in-container service detection (see // containers::with_service_probing). Background enumerations reuse the // same helper and must not exec into every container. match web::block(|| containers::with_service_probing(containers::docker_list_all_cached)).await { Ok(containers) => HttpResponse::Ok().json(containers), // A non-OK (not an empty 200) so the frontend keeps the current list // instead of blanking it on a rare blocking-pool error. Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "docker list unavailable"})), } } /// GET /api/search?q= — local resource search powering the top-bar global /// search. Matches Docker + LXC containers, VMs, and network interfaces/VLANs /// on THIS node by name (+ id / IP / MAC where useful). Returns a small capped /// payload tagged with the `view` to navigate to; the frontend calls this on /// the local node and proxies it to every online peer, then aggregates — so a /// single box searches the whole cluster. Reads cached container lists, so it's /// cheap to fan out. pub async fn global_search( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let q = query.get("q").map(|s| s.trim().to_lowercase()).unwrap_or_default(); if q.len() < 2 { // Avoid fanning out a whole-fleet search on a single keystroke. return HttpResponse::Ok().json(serde_json::json!({ "results": [] })); } // Every lookup below shells out (`ip` for interfaces) or reads a // cache/lock, so run the whole gather on the blocking pool — a search // fan-out must never park an actix async worker thread. let state = state.clone(); let results: Vec = web::block(move || { const PER_KIND: usize = 8; let mut results: Vec = Vec::new(); // Docker containers → Docker view for c in containers::docker_list_all_cached().into_iter() .filter(|c| c.name.to_lowercase().contains(&q) || c.id.to_lowercase().contains(&q)) .take(PER_KIND) { results.push(serde_json::json!({ "kind": "docker", "label": "Docker", "name": c.name, "detail": c.image, "state": c.state, "view": "containers", })); } // LXC containers → LXC view for c in containers::lxc_list_all_cached().into_iter() .filter(|c| c.name.to_lowercase().contains(&q) || c.id.to_lowercase().contains(&q) || c.ip_address.to_lowercase().contains(&q)) .take(PER_KIND) { results.push(serde_json::json!({ "kind": "lxc", "label": "LXC", "name": c.name, "detail": c.ip_address, "state": c.state, "view": "lxc", })); } // VMs → Proxmox combined view on PVE hosts, native VM view otherwise let vm_view = if containers::is_proxmox() { "pve-resources" } else { "vms" }; let vms = state.vms.lock().unwrap().list_vms(); for vm in vms.into_iter() .filter(|v| v.name.to_lowercase().contains(&q)) .take(PER_KIND) { results.push(serde_json::json!({ "kind": "vm", "label": "VM", "name": vm.name, "detail": format!("{} vCPU · {} MB", vm.cpus, vm.memory_mb), "view": vm_view, })); } // Network interfaces / VLANs → Networking view for nic in networking::list_interfaces().into_iter() .filter(|n| n.name.to_lowercase().contains(&q) || n.mac.to_lowercase().contains(&q) || n.addresses.iter().any(|a| a.address.to_lowercase().contains(&q))) .take(PER_KIND) { let detail = if nic.is_vlan { format!("VLAN {}{}", nic.vlan_id.map(|v| v.to_string()).unwrap_or_default(), nic.parent.as_ref().map(|p| format!(" on {}", p)).unwrap_or_default()) } else { nic.addresses.first().map(|a| a.address.clone()).unwrap_or_else(|| nic.mac.clone()) }; results.push(serde_json::json!({ "kind": "network", "label": "Network", "name": nic.name, "detail": detail, "state": nic.state, "view": "networking", })); } results }).await.unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "results": results })) } /// GET /api/containers/cluster — list every Docker + LXC container /// across this node and every reachable cluster peer. Same fan-out /// pattern as /api/gateways/cluster and /api/array/cluster. Each /// entry is tagged with `runtime` ("docker" or "lxc"), `node_id`, and /// `node_hostname` so the frontend can group / filter without an /// extra round-trip. /// /// Powers the status-page Container monitor picker — needs to work /// when the operator is configuring a status page on a federated / /// remote cluster, where the local server's node-proxy can't reach /// the remote peers but the remote cluster's gateway node can. /// Calling /api/containers/cluster on a remote cluster (via the /// status page's spApiBase) returns *that* cluster's full inventory. pub async fn containers_cluster(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Self — both runtimes. let self_node = state.cluster.get_all_nodes().into_iter().find(|n| n.is_self); let self_id = state.node_id.clone(); let self_hostname = self_node.as_ref().map(|n| n.hostname.clone()).unwrap_or_default(); let mut all: Vec = Vec::new(); for c in containers::docker_list_all_cached() { if let Ok(mut v) = serde_json::to_value(&c) { if let Some(obj) = v.as_object_mut() { obj.insert("node_id".into(), serde_json::json!(self_id)); obj.insert("node_hostname".into(), serde_json::json!(self_hostname)); } all.push(v); } } for c in containers::lxc_list_all_cached() { if let Ok(mut v) = serde_json::to_value(&c) { if let Some(obj) = v.as_object_mut() { obj.insert("node_id".into(), serde_json::json!(self_id)); obj.insert("node_hostname".into(), serde_json::json!(self_hostname)); } all.push(v); } } // Peers — fan out in parallel. Same shape as // gateways_cluster/array_cluster: try the existing /api/containers/* // endpoints with the cluster secret. Proxmox-typed nodes don't run // our containers module so we skip them. let peers: Vec<_> = state.cluster.get_all_nodes().into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack" && n.online) .collect(); let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let mut handles = Vec::new(); for peer in &peers { let docker_urls = build_node_urls(&peer.address, peer.port, "/api/containers/docker"); let lxc_urls = build_node_urls(&peer.address, peer.port, "/api/containers/lxc"); let secret = secret.clone(); let peer_id = peer.self_id.clone().unwrap_or_else(|| peer.id.clone()); let peer_host = peer.hostname.clone(); let h = tokio::spawn(async move { let docker_fut = async { for url in &docker_urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret).send().await && resp.status().is_success() && let Ok(v) = resp.json::>().await { return v; } } Vec::new() }; let lxc_fut = async { for url in &lxc_urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret).send().await && resp.status().is_success() && let Ok(v) = resp.json::>().await { return v; } } Vec::new() }; let (docker_v, lxc_v) = tokio::join!(docker_fut, lxc_fut); (peer_id, peer_host, docker_v, lxc_v) }); handles.push(h); } for h in handles { if let Ok((pid, host, docker_v, lxc_v)) = h.await { for mut entry in docker_v.into_iter().chain(lxc_v) { if let Some(obj) = entry.as_object_mut() { obj.insert("node_id".into(), serde_json::json!(pid)); obj.insert("node_hostname".into(), serde_json::json!(host)); } all.push(entry); } } } HttpResponse::Ok().json(serde_json::json!({ "containers": all })) } /// GET /api/containers/docker/search?q= — search Docker Hub pub async fn docker_search( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let q = query.get("q").cloned().unwrap_or_default(); if q.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing query parameter 'q'" })); } let results = containers::docker_search(&q); HttpResponse::Ok().json(results) } #[derive(Deserialize)] pub struct DockerPullRequest { pub image: String, } /// POST /api/containers/docker/pull — pull a Docker image pub async fn docker_pull( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match containers::docker_pull(&body.image) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct DockerCreateRequest { pub name: String, pub image: String, pub ports: Option>, pub env: Option>, pub wolfnet_ip: Option, pub memory_limit: Option, pub cpu_cores: Option, pub storage_limit: Option, /// Volume mounts: ["host:container", "volume_name:/data", ...] #[serde(default)] pub volumes: Vec, } /// POST /api/containers/docker/create — create a Docker container pub async fn docker_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let ports = body.ports.as_deref().unwrap_or(&[]); let env = body.env.as_deref().unwrap_or(&[]); let wolfnet_ip = body.wolfnet_ip.as_deref(); let memory = body.memory_limit.as_deref(); let cpus = body.cpu_cores.as_deref(); let storage = body.storage_limit.as_deref(); match containers::docker_create(containers::DockerCreateOptions { name: &body.name, image: &body.image, ports, env, wolfnet_ip, memory, cpus, storage, volumes: &body.volumes }) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), // Port-conflict pre-flight rejections start with "Cannot // create container `…`: requested host port …" — that's a // user input error, not a server fault, so return 409 // Conflict instead of 500. The frontend's create-container // handler already shows the JSON `error` field as a toast, // so the operator gets the named-owner explanation directly. Err(e) if e.starts_with("Cannot create container") => HttpResponse::Conflict().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/containers/lxc/templates — list available LXC templates pub async fn lxc_templates(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let templates = containers::lxc_list_templates(); HttpResponse::Ok().json(templates) } #[derive(Deserialize)] pub struct LxcCreateRequest { pub name: String, pub distribution: String, pub release: String, pub architecture: String, pub wolfnet_ip: Option, pub storage_path: Option, /// Where the distro template tarball should live. On Proxmox this is /// the PVE storage id that holds `vztmpl` content (defaults to "local"). /// On native LXC it's used as LXC_CACHE_PATH for lxc-create so the /// downloaded tarball goes there instead of /var/cache/lxc. #[serde(default)] pub template_storage: Option, pub root_password: Option, pub memory_limit: Option, pub cpu_cores: Option, /// Network mode: "wolfnet" (default), "bridge", or "host". When /// "bridge" is set, bridge_name / bridge_ip / bridge_gateway control /// the LXC veth network config. When "host" is set, the container /// shares the host's network namespace. #[serde(default)] pub network_mode: Option, /// Bridge name for mode=bridge (e.g. "lxcbr0", "vmbr0"). Ignored for /// other modes. #[serde(default)] pub bridge_name: Option, /// Static IP in CIDR form for mode=bridge+static (e.g. "192.168.10.50/24"). /// If absent or empty, the container uses DHCP from the bridge. #[serde(default)] pub bridge_ip: Option, /// Gateway for mode=bridge+static. Usually the router IP on that subnet. #[serde(default)] pub bridge_gateway: Option, /// Free-text operator notes / description. Persisted via `pct set /// --description` (Proxmox) or the WolfStack sidecar (native LXC). #[serde(default)] pub notes: Option, } /// POST /api/containers/lxc/create — create an LXC container from template pub async fn lxc_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Auto-assign WolfNet IP only when the user chose WolfNet mode (or // no mode = legacy/default). Bridge and Host modes explicitly don't // want a WolfNet IP — auto-assigning one from the pool was a bug // that burned addresses the user never intended to use and // confused the "simple WolfNet setup" path by attaching WolfNet // even on bridge-mode containers. let net_mode = body.network_mode.as_deref().unwrap_or("wolfnet"); let wolfnet_ip = if net_mode == "wolfnet" || net_mode.is_empty() { match body.wolfnet_ip.as_deref() { Some(ip) if !ip.is_empty() => Some(ip.to_string()), _ => containers::next_available_wolfnet_ip(), } } else { None }; // On Proxmox, pct_create handles password, memory, and CPU natively if containers::is_proxmox() { let storage = body.storage_path.as_deref(); let template_storage = body.template_storage.as_deref(); let password = body.root_password.as_deref(); // Parse memory limit (e.g. "512m" -> 512, "2g" -> 2048) let memory_mb = body.memory_limit.as_deref().and_then(|m| { let m = m.trim().to_lowercase(); if m.ends_with('g') { m.trim_end_matches('g').parse::().ok().map(|v| v * 1024) } else if m.ends_with('m') { m.trim_end_matches('m').parse::().ok() } else { m.parse::().ok() } }); let cpu_cores = body.cpu_cores.as_deref().and_then(|c| c.parse::().ok()); return match containers::pct_create_api(containers::PctCreateOptions { name: &body.name, distribution: &body.distribution, release: &body.release, architecture: &body.architecture, storage_id: storage, template_storage_id: template_storage, root_password: password, memory_mb, cpu_cores, wolfnet_ip: wolfnet_ip.as_deref(), net_mode, bridge: body.bridge_name.as_deref(), bridge_ip: body.bridge_ip.as_deref(), bridge_gateway: body.bridge_gateway.as_deref(), }) { Ok((vmid, mut msg)) => { // Notes / description — set after the CT exists so `pct set // --description` has a target. Non-fatal: a notes failure must // not fail the whole create. let notes = body.notes.as_deref().unwrap_or(""); if !notes.is_empty() && let Err(e) = containers::lxc_set_notes(&vmid.to_string(), notes) { msg = format!("{} — Notes warning: {}", msg, e); } HttpResponse::Ok().json(serde_json::json!({ "message": msg })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; } // Standalone LXC path let storage = body.storage_path.as_deref(); let template_storage = body.template_storage.as_deref(); match containers::lxc_create(&body.name, &body.distribution, &body.release, &body.architecture, storage, template_storage) { Ok(msg) => { let mut messages = vec![msg]; // Set root password if provided if let Some(ref password) = body.root_password && !password.is_empty() { match containers::lxc_set_root_password(&body.name, password) { Ok(pw_msg) => messages.push(pw_msg), Err(e) => messages.push(format!("Password warning: {}", e)), } } // Set resource limits if provided let memory = body.memory_limit.as_deref(); let cpus = body.cpu_cores.as_deref(); match containers::lxc_set_resource_limits(&body.name, memory, cpus) { Ok(Some(rl_msg)) => messages.push(rl_msg), Err(e) => messages.push(format!("Resource limit warning: {}", e)), _ => {} } // Network — three modes: // "wolfnet" (default): attach to WolfNet overlay with auto or manual IP // "bridge": configure LXC veth on the specified bridge (DHCP or static) // "host": no network namespace isolation let net_mode = body.network_mode.as_deref().unwrap_or("wolfnet"); match net_mode { "wolfnet" | "" => { if let Some(ref ip) = wolfnet_ip { match containers::lxc_attach_wolfnet(&body.name, ip) { Ok(wn_msg) => messages.push(wn_msg), Err(e) => messages.push(format!("WolfNet warning: {}", e)), } } } "bridge" => { let bridge = body.bridge_name.as_deref().unwrap_or("lxcbr0"); let config_path = format!("{}/{}/config", containers::lxc_base_dir(&body.name), body.name); // Replace the existing lxc.net.0.* block with our bridge config. // Read → filter out old net lines → append fresh ones. This is // safe because lxc-create already wrote a net block and we're // just changing the bridge and IP assignment. let existing = std::fs::read_to_string(&config_path).unwrap_or_default(); let mut lines: Vec = existing.lines() .filter(|l| !l.trim().starts_with("lxc.net.0.")) .map(|s| s.to_string()) .collect(); lines.push("lxc.net.0.type = veth".to_string()); lines.push(format!("lxc.net.0.link = {}", bridge)); lines.push("lxc.net.0.flags = up".to_string()); // Generate a random MAC so each container has a unique one. let mac = format!("00:16:3e:{:02x}:{:02x}:{:02x}", rand_byte(), rand_byte(), rand_byte()); lines.push(format!("lxc.net.0.hwaddr = {}", mac)); // Static bridge IP: set the liblxc address AND write the // container's OWN network config so its init doesn't DHCP // over the static address (wabil 2026-06-26: the veth got // the static IP but the image's default DHCP overrode it). // Only a REAL IPv4 CIDR counts as static — a non-IP value // (e.g. "dhcp") or junk falls through to DHCP rather than // being written as a bogus address. Gateway must be a valid // IPv4 or it's dropped (never injected into rootfs files). let static_cidr = body.bridge_ip.as_deref() .map(containers::normalize_bridge_cidr) .filter(|s| containers::is_ipv4_cidr(s)); let static_gw = body.bridge_gateway.as_deref() .map(str::trim) .filter(|g| g.parse::().is_ok()); if let Some(ref cidr) = static_cidr { lines.push(format!("lxc.net.0.ipv4.address = {}", cidr)); if let Some(gw) = static_gw { lines.push(format!("lxc.net.0.ipv4.gateway = {}", gw)); } } lines.push(String::new()); // trailing newline // Write the host LXC config first; only then the in-container // static config, so a host-config failure is reported before // we touch the rootfs and the messages stay accurate. if let Err(e) = std::fs::write(&config_path, lines.join("\n")) { messages.push(format!("Bridge config warning: {}", e)); } else { messages.push(format!("Network: veth on {} ({})", bridge, if static_cidr.is_some() { "static" } else { "DHCP" })); if let Some(ref cidr) = static_cidr && let Err(e) = containers::write_lxc_bridge_static_config(&body.name, cidr, static_gw) { messages.push(format!( "Static IP warning: in-container network config not fully written ({}) — the container may still come up via DHCP", e)); } } } "host" => { let config_path = format!("{}/{}/config", containers::lxc_base_dir(&body.name), body.name); let existing = std::fs::read_to_string(&config_path).unwrap_or_default(); let mut lines: Vec = existing.lines() .filter(|l| !l.trim().starts_with("lxc.net.0.")) .map(|s| s.to_string()) .collect(); lines.push("lxc.net.0.type = none".to_string()); lines.push(String::new()); if let Err(e) = std::fs::write(&config_path, lines.join("\n")) { messages.push(format!("Host network config warning: {}", e)); } else { messages.push("Network: host (no isolation)".to_string()); } } _ => {} } // Notes / description — write the native-LXC sidecar. let notes = body.notes.as_deref().unwrap_or(""); if !notes.is_empty() && let Err(e) = containers::lxc_set_notes(&body.name, notes) { messages.push(format!("Notes warning: {}", e)); } HttpResponse::Ok().json(serde_json::json!({ "message": messages.join(" — ") })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Quick pseudo-random byte for MAC addresses. NOT crypto-grade — just /// needs to be unique-enough per container so bridges don't confuse them. /// Reads 1 byte from /dev/urandom which is always non-blocking on Linux. fn rand_byte() -> u8 { use std::io::Read; let mut buf = [0u8; 1]; if let Ok(mut f) = std::fs::File::open("/dev/urandom") { let _ = f.read_exact(&mut buf); } else { // Fallback: nanos-derived (non-repeatable across fast calls but better than nothing). let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.subsec_nanos()).unwrap_or(0); buf[0] = (nanos & 0xFF) as u8; } buf[0] } /// GET /api/storage/remote-list?url= — proxy storage list from a remote WolfStack node pub async fn remote_storage_list( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match query.get("url") { Some(u) if !u.is_empty() => u.clone(), _ => return HttpResponse::BadRequest().json(serde_json::json!({"error": "url parameter required"})), }; let urls = build_external_urls(&target, "/api/storage/list"); let client = &*API_HTTP_CLIENT; // Only hand our cluster secret to a genuine cluster node — never to an // arbitrary operator-supplied URL (which could be attacker-controlled and // would capture the fleet-root credential). let attach_secret = target_is_cluster_node(&state, &target); let mut last_err = String::new(); for url in &urls { let mut rb = client.get(url).timeout(std::time::Duration::from_secs(10)); if attach_secret { rb = rb.peer_auth(state.cluster_secret.clone()); } match rb.send().await { Ok(r) if r.status().is_success() => { let body = r.text().await.unwrap_or_default(); return HttpResponse::Ok() .content_type("application/json") .body(body); } Ok(r) => { let status = r.status(); last_err = format!("{}: HTTP {}", url, status); let _ = r.bytes().await; continue; } Err(e) => { last_err = format!("{}: {}", url, e); continue; } } } tracing::warn!("remote_storage_list failed for '{}': {}", target, last_err); HttpResponse::BadGateway().json(serde_json::json!({"error": format!("Could not reach remote cluster: {}", last_err)})) } /// GET /api/storage/filesystems — list real host mountpoints. Unlike /// /api/storage/list this never returns PVE storage IDs; it walks the /// live metrics disk list so callers that need a filesystem *path* /// (LXC rsync migrate, anything writing via bind mount) don't get /// handed something like `wolfpool` or `local-zfs` they can't cd into. pub async fn storage_filesystems(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Writable on-disk filesystems that actually host container data. // NFS / CIFS etc are intentionally excluded — rsync across them // works but loses perms/xattrs that -aHAX promises. const WRITABLE_FS_TYPES: &[&str] = &[ "ext4", "ext3", "ext2", "xfs", "btrfs", "zfs", "f2fs", "reiserfs", "jfs", ]; let node = state.cluster.get_node(&state.cluster.self_id); let disks = node.as_ref().and_then(|n| n.metrics.as_ref()) .map(|m| m.disks.clone()) .unwrap_or_default(); let items: Vec = disks.iter() .filter(|d| { let fs = d.fs_type.to_ascii_lowercase(); WRITABLE_FS_TYPES.iter().any(|t| fs == *t || fs.starts_with(&format!("{}.", t))) && d.available_bytes > 1024 * 1024 * 1024 // > 1 GiB free && !d.mount_point.starts_with("/snap") && !d.mount_point.starts_with("/boot") && !d.mount_point.starts_with("/var/lib/docker/") && !d.mount_point.starts_with("/var/lib/containers/") }) .map(|d| serde_json::json!({ "mount_point": d.mount_point, "fs_type": d.fs_type, "total_bytes": d.total_bytes, "used_bytes": d.used_bytes, "available_bytes": d.available_bytes, })) .collect(); HttpResponse::Ok().json(serde_json::json!({ "filesystems": items, })) } /// GET /api/storage/list — list available storage locations (Proxmox-aware) pub async fn storage_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let is_pve = containers::is_proxmox(); if is_pve { // Return Proxmox storage IDs let storages = containers::pvesm_list_storage(); let items: Vec = storages.iter().map(|s| { serde_json::json!({ "id": s.id, "type": s.storage_type, "status": s.status, "total_bytes": s.total_bytes, "used_bytes": s.used_bytes, "available_bytes": s.available_bytes, "content": s.content, "path": s.path, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "proxmox": true, "storages": items, })) } else { // Return filesystem-based storage let node = state.cluster.get_node(&state.cluster.self_id); let disks = node.as_ref().and_then(|n| n.metrics.as_ref()) .map(|m| &m.disks) .cloned() .unwrap_or_default(); let items: Vec = disks.iter() .filter(|d| d.available_bytes > 1073741824) // > 1GB free .map(|d| serde_json::json!({ "id": d.mount_point, "type": "dir", "status": "active", "total_bytes": d.total_bytes, "used_bytes": d.used_bytes, "available_bytes": d.available_bytes, "content": ["rootdir", "images"], })) .collect(); HttpResponse::Ok().json(serde_json::json!({ "proxmox": false, "storages": items, })) } } /// GET /api/wolfnet/status — get WolfNet networking status for container creation /// Queries all cluster nodes for used IPs to avoid collisions pub async fn wolfnet_network_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Collect used IPs from all remote cluster nodes let mut remote_used: Vec = Vec::new(); let nodes = state.cluster.get_all_nodes(); let client = &*API_HTTP_CLIENT; for node in &nodes { if node.is_self || !node.online { continue; } let urls = build_node_urls(&node.address, node.port, "/api/wolfnet/used-ips"); for url in &urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(3)) .peer_auth(state.cluster_secret.clone()) .send().await { if let Ok(ips) = resp.json::>().await { for ip_str in ips { let parts: Vec<&str> = ip_str.split('.').collect(); if parts.len() == 4 && let Ok(last) = parts[3].parse::() { remote_used.push(last); } } } break; // Success on this node } } } let status = containers::wolfnet_status(&remote_used); HttpResponse::Ok().json(status) } /// GET /api/ports — return this node's persistent port config (api/inter_node/status). pub async fn get_ports(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::ports::PortConfig::load()) } /// POST /api/ports — update this node's persistent port config. /// Changes take effect on next restart; we don't try to rebind live listeners. pub async fn set_ports(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = body.into_inner(); // Sanity: reject anything outside the unprivileged range to avoid foot-guns. for (name, p) in [("api", cfg.api), ("inter_node", cfg.inter_node), ("status", cfg.status)] { if p < 1024 { return HttpResponse::BadRequest() .json(serde_json::json!({"error": format!("{} port {} is in the privileged range (<1024)", name, p)})); } } if cfg.api == cfg.inter_node || cfg.api == cfg.status || cfg.inter_node == cfg.status { return HttpResponse::BadRequest() .json(serde_json::json!({"error": "api, inter_node and status ports must all differ"})); } if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(serde_json::json!({"saved": true, "restart_required": true})) } // ─── Reverse proxy configuration ──────────────────────────────────────── /// GET /api/reverse-proxy/config — public base URL override for building /// shareable links (status pages, cluster browser) when WolfStack is /// served through a reverse proxy on a domain that differs from the /// node's internal address. pub async fn reverse_proxy_config_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::reverse_proxy::ReverseProxyConfig::load()) } /// POST /api/reverse-proxy/config — validate and persist the override. pub async fn reverse_proxy_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = body.into_inner().normalised(); if !cfg.public_base_url.is_empty() { let u = &cfg.public_base_url; if !(u.starts_with("http://") || u.starts_with("https://")) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "public_base_url must start with http:// or https://" })); } if u.contains(' ') || u.contains('\n') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "public_base_url must not contain whitespace" })); } } if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(serde_json::json!({"saved": true, "config": cfg})) } // ─── Certbot / SSL certificates ───────────────────────────────────────── /// GET /api/certs — list every Let's Encrypt cert on disk, with expiry. /// Cert list decorated with replication state, shared by `/api/certs` /// and the local row of `/api/certs/cluster` so the two can't drift. /// /// `replicated` = this node pushes it to peers. `replica_of` = it /// ARRIVED from that peer, which is what tells the UI to suppress Renew /// (a replica has no certbot renewal config, so renewing it is /// meaningless — the owner does that). fn certs_list_payload() -> serde_json::Value { let cfg = crate::certbot::replication::ReplicationConfig::load(); let replicas = crate::certbot::replication::ReplicaStore::load(); let certs: Vec = crate::certbot::list_certs() .into_iter() .map(|c| { let replica_of = replicas.get(&c.name).map(|r| r.source_hostname.clone()); let mut v = serde_json::to_value(&c).unwrap_or_else(|_| serde_json::json!({})); if let Some(o) = v.as_object_mut() { o.insert("replicated".into(), serde_json::json!(cfg.is_replicated(&c.name))); o.insert("replica_of".into(), serde_json::json!(replica_of)); } v }) .collect(); serde_json::json!({ "installed": crate::certbot::is_installed(), "config": crate::certbot::CertbotConfig::load(), "certs": certs, }) } pub async fn certs_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match web::block(certs_list_payload).await { Ok(v) => HttpResponse::Ok().json(v), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": e.to_string() })), } } /// GET /api/certs/cluster — aggregated cert list across every node in /// this cluster. Each row carries `node_id` / `hostname` so the UI can /// show a single screen of every cert on every node and route the /// Issue/Renew/Delete buttons through `/api/nodes/{id}/proxy/api/certs`. /// /// (klasSponsor + PapaSchlumpf 2026-05-17: "allow one node to provision /// and monitor all certs for all nodes in cluster" — they don't want /// keys replicated, just one screen.) pub async fn certs_cluster_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let nodes = state.cluster.get_all_nodes(); let self_id = crate::agent::self_node_id(); let secret = state.cluster_secret.clone(); let mut rows: Vec = Vec::new(); // Local first — direct call, no HTTP round-trip. if let Some(self_node) = nodes.iter().find(|n| n.is_self).cloned() { // Same payload builder as /api/certs, so the local row carries // the replication fields exactly like the peer rows do. let mut row = web::block(certs_list_payload).await .unwrap_or_else(|_| serde_json::json!({ "certs": [] })); if let Some(o) = row.as_object_mut() { o.insert("node_id".into(), serde_json::json!(self_node.id)); o.insert("hostname".into(), serde_json::json!(self_node.hostname)); o.insert("cluster_name".into(), serde_json::json!(self_node.cluster_name)); o.insert("is_self".into(), serde_json::json!(true)); } rows.push(row); } // Then every other online wolfstack node in parallel. let mut futs: Vec<_> = Vec::new(); for node in nodes.iter() { if node.is_self || node.id == self_id { continue; } if !node.online { continue; } if node.node_type != "wolfstack" { continue; } let node = node.clone(); let secret = secret.clone(); futs.push(async move { let urls = build_node_urls(&node.address, node.port, "/api/certs"); let client = &*API_HTTP_CLIENT; let mut last_err = String::new(); for url in &urls { match client.get(url) .peer_auth(&secret) .timeout(std::time::Duration::from_secs(8)) .send().await { Ok(r) if r.status().is_success() => { match r.json::().await { Ok(mut v) => { // Stamp node identity onto the row so the // UI can group + route. cluster_name on // each row also lets a future fleet view // (v23.13) merge multiple clusters. if let Some(obj) = v.as_object_mut() { obj.insert("node_id".into(), serde_json::json!(node.id)); obj.insert("hostname".into(), serde_json::json!(node.hostname)); obj.insert("cluster_name".into(), serde_json::json!(node.cluster_name)); obj.insert("is_self".into(), serde_json::json!(false)); } return v; } Err(e) => { last_err = format!("decode: {}", e); continue; } } } Ok(r) => { last_err = format!("HTTP {}", r.status()); continue; } Err(e) => { last_err = format!("{}: {}", url, e); continue; } } } // Emit an error row so the operator sees WHICH nodes were // unreachable rather than them silently disappearing from // the aggregated view. Matches the Fleet Security pattern // (v23.10.5: "surface WHICH nodes are unreachable"). serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "cluster_name": node.cluster_name, "is_self": false, "error": last_err, }) }); } let peer_rows = futures::future::join_all(futs).await; rows.extend(peer_rows); HttpResponse::Ok().json(serde_json::json!({ "nodes": rows })) } // ───────────────── certificate replication ───────────────── // // Opt-in push of a cert (including its private key) from the node that // issues and renews it to the cluster peers that need to SERVE it. See // `certbot::replication` for why replicas are inert and how renewal // re-replication is detected. /// GET /api/certs/replication — this node's replicate list plus the /// replicas it currently holds from other nodes, so one screen can show /// both directions. pub async fn certs_replication_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (cfg, store) = web::block(|| { ( crate::certbot::replication::ReplicationConfig::load(), crate::certbot::replication::ReplicaStore::load(), ) }) .await .unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "certs": cfg.certs, "replicas": store.replicas, })) } #[derive(Deserialize)] pub struct CertReplicationSaveRequest { /// Full desired list of cert names to replicate from this node. /// Replace-semantics: what you send is what you get. pub certs: Vec, } /// POST /api/certs/replication — set which certs this node replicates. /// Kicks an immediate reconcile so enabling (or disabling) takes effect /// without waiting for the periodic pass. pub async fn certs_replication_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut certs = body.into_inner().certs; certs.sort(); certs.dedup(); // Validate before saving: a name that can't be replicated should be // rejected at the point the operator sets it, not silently skipped // by the reconcile loop later. for name in &certs { if !crate::certbot::replication::is_safe_cert_name(name) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("invalid certificate name '{}'", name) })); } } let cfg = crate::certbot::replication::ReplicationConfig { certs: certs.clone() }; if let Err(e) = web::block(move || cfg.save()).await .unwrap_or_else(|e| Err(e.to_string())) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { reconcile_cert_replication(cluster, secret).await; }); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "certs": certs })) } /// GET /api/certs/replication/state — peer-to-peer. Reports the digests /// of replicas held here (so the owner can diff without shipping keys) /// and the lineages this node owns (so the owner can report a conflict /// instead of retrying a push that will always be refused). pub async fn certs_replication_state( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let st = web::block(crate::certbot::replication::local_state) .await .unwrap_or_default(); HttpResponse::Ok().json(st) } /// POST /api/certs/replication/push — peer-to-peer receiver. Writes an /// incoming lineage and reloads the proxy if anything actually changed. pub async fn certs_replication_push( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let bundle = body.into_inner(); let name = bundle.name.clone(); let applied = web::block(move || { let r = crate::certbot::replication::apply_bundle(&bundle); // Reload inside the blocking context so the systemctl call isn't // sitting on the async runtime. if matches!(&r, Ok(a) if a.changed) { crate::certbot::replication::reload_after_replica(); } r }) .await; match applied { Ok(Ok(a)) => { if a.changed { tracing::info!("cert replication: applied '{}' from peer", name); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "changed": a.changed })) } Ok(Err(e)) => { tracing::warn!("cert replication: refused '{}': {}", name, e); HttpResponse::BadRequest().json(serde_json::json!({ "error": e })) } Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": e.to_string() })), } } #[derive(Deserialize)] pub struct CertReplicationPruneRequest { /// Node id of the owner doing the pruning. pub source_node_id: String, /// Names that owner still replicates. Anything else it previously /// sent us is removed. pub keep: Vec, } /// POST /api/certs/replication/prune — peer-to-peer. Drops replicas the /// sending owner no longer replicates. pub async fn certs_replication_prune( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let b = body.into_inner(); let removed = web::block(move || { let r = crate::certbot::replication::prune(&b.source_node_id, &b.keep); if matches!(&r, Ok(v) if !v.is_empty()) { crate::certbot::replication::reload_after_replica(); } r }) .await; match removed { Ok(Ok(names)) => { if !names.is_empty() { tracing::info!("cert replication: pruned {:?}", names); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "removed": names })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": e.to_string() })), } } /// Owner-side reconcile. For every cert this node replicates, ask each /// online peer what it holds and push only what differs — then prune /// what the operator has turned off. /// /// Diff-then-push (rather than blind push) is what makes this safe to /// run on a timer: a renewal changes the digest and is picked up on the /// next pass no matter WHICH mechanism performed the renewal, while a /// steady state costs one small GET per peer and moves no key material. /// /// Runs unconditionally rather than short-circuiting on an empty list: /// the prune leg is what cleans up after the last cert is switched off, /// and it must still reach a peer that was offline at the time. The cost /// is one GET + one small POST per peer per pass, against a cluster that /// already polls every node every 10 seconds. pub async fn reconcile_cert_replication( cluster: std::sync::Arc, cluster_secret: String, ) { let nodes = cluster.get_all_nodes(); let self_id = crate::agent::self_node_id(); let self_hostname = nodes .iter() .find(|n| n.is_self) .map(|n| n.hostname.clone()) .unwrap_or_default(); let sid = self_id.clone(); let shost = self_hostname.clone(); let (keep, bundles) = match tokio::task::spawn_blocking(move || { let cfg = crate::certbot::replication::ReplicationConfig::load(); let replicas = crate::certbot::replication::ReplicaStore::load(); let mut bundles = Vec::new(); // `keep` is the CONFIGURED list, deliberately not "the ones we // managed to read". Deriving it from successful reads would mean // a transient IO error dropped the name from `keep` and the prune // leg then DELETED a perfectly good replica off every peer. Prune // must express operator intent ("stop replicating this"), never a // momentary local failure — so cert deletion removes the name // from this config instead (see certs_delete). let keep = cfg.certs.clone(); for name in &cfg.certs { // A replica must never be re-replicated onward — the owner // is the node holding the certbot renewal config. Without // this, B could push A's cert back to C and muddy who owns // what. if replicas.is_replica(name) { tracing::warn!( "cert replication: '{}' is itself a replica on this node — not re-replicating", name ); continue; } match crate::certbot::replication::read_bundle(name, &sid, &shost) { Ok(b) => bundles.push(b), Err(e) => tracing::warn!("cert replication: skipping '{}': {}", name, e), } } (keep, bundles) }) .await { Ok(v) => v, Err(e) => { tracing::warn!("cert replication: gather failed: {}", e); return; } }; let client = &*API_HTTP_CLIENT; for node in nodes { if node.is_self || node.id == self_id { continue; } if !node.online { continue; } if node.node_type != "wolfstack" { continue; } // What does this peer already have? let mut peer_state: Option = None; for url in build_node_urls(&node.address, node.port, "/api/certs/replication/state") { match client.get(&url) .peer_auth(&cluster_secret) .timeout(std::time::Duration::from_secs(10)) .send().await { Ok(r) if r.status().is_success() => { if let Ok(v) = r.json::().await { peer_state = Some(v); break; } } Ok(r) => { let _ = r.bytes().await; } Err(_) => {} } } let Some(peer_state) = peer_state else { tracing::warn!( "cert replication: could not read state from {} ({}) — skipping this pass", node.hostname, node.address ); continue; }; for bundle in &bundles { // The peer issues this cert itself — pushing would be // refused every pass, so say so once and move on. if peer_state.owned.iter().any(|n| n == &bundle.name) { tracing::warn!( "cert replication: {} owns '{}' itself — not replacing it with a replica", node.hostname, bundle.name ); continue; } if peer_state.replicas.get(&bundle.name) == Some(&bundle.digest) { continue; // already current } let body = match serde_json::to_string(bundle) { Ok(b) => b, Err(e) => { tracing::warn!("cert replication: serialise '{}': {}", bundle.name, e); continue; } }; let mut pushed = false; let mut last_err = String::new(); for url in build_node_urls(&node.address, node.port, "/api/certs/replication/push") { match client.post(&url) .peer_auth(&cluster_secret) .header("Content-Type", "application/json") .timeout(std::time::Duration::from_secs(20)) .body(body.clone()) .send().await { Ok(r) if r.status().is_success() => { let _ = r.bytes().await; pushed = true; break; } Ok(r) => { let status = r.status(); let detail = r.text().await.unwrap_or_default(); last_err = format!("HTTP {} — {}", status, detail); } Err(e) => last_err = format!("{} ({})", e, url), } } if pushed { tracing::info!("cert replication: '{}' → {}", bundle.name, node.hostname); } else { tracing::warn!( "cert replication: '{}' → {} FAILED: {}", bundle.name, node.hostname, last_err ); } } // Prune whatever this owner no longer replicates. let prune_body = serde_json::json!({ "source_node_id": self_id, "keep": keep }).to_string(); for url in build_node_urls(&node.address, node.port, "/api/certs/replication/prune") { match client.post(&url) .peer_auth(&cluster_secret) .header("Content-Type", "application/json") .timeout(std::time::Duration::from_secs(10)) .body(prune_body.clone()) .send().await { Ok(r) if r.status().is_success() => { let _ = r.bytes().await; break; } Ok(r) => { let _ = r.bytes().await; } Err(_) => {} } } } } #[derive(Deserialize)] pub struct CertIssueRequest { pub domains: Vec, #[serde(default)] pub email: String, /// "webroot" (default) or "dns-". #[serde(default)] pub challenge: String, /// Path to an uploaded DNS provider credentials INI, if using DNS-01. /// Legacy path — prefer `dns_provider_id` which uses the cluster /// store and keeps the secret out of the per-request payload. #[serde(default)] pub dns_credentials_path: String, /// ID of a saved DNS provider (see /api/dns-providers). When set, /// the cert is issued via DNS-01 with that provider's credentials, /// regardless of `challenge` — set this and you also get wildcard /// support for free. #[serde(default)] pub dns_provider_id: String, #[serde(default)] pub dry_run: bool, } /// POST /api/certs — issue a new cert. Runs certbot in-process and /// returns its stdout so the UI can surface ACME errors verbatim /// (they're usually self-explanatory — rate limits, DNS mismatch, etc.) pub async fn certs_issue( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let b = body.into_inner(); let domains = b.domains.clone(); let email = b.email.clone(); let dry_run = b.dry_run; // `dns_provider_id` wins over `challenge`: if the operator picked a // saved provider, we issue via that regardless of the radio button // setting. Wildcard support drops out for free — pass `*.zone.tld` // in `domains` and certbot does the rest. let result = if !b.dns_provider_id.is_empty() { let pid = b.dns_provider_id.clone(); web::block(move || crate::certbot::issue_via_provider(&domains, &email, &pid, dry_run)).await } else { let challenge = if b.challenge.is_empty() { "webroot".to_string() } else { b.challenge }; let creds: Option = if b.dns_credentials_path.is_empty() { None } else { Some(b.dns_credentials_path.clone()) }; web::block(move || crate::certbot::issue(&domains, &email, &challenge, creds.as_deref(), dry_run)).await }; // A newly issued cert may already be on the replicate list (re-issue // of an existing name), so propagate immediately rather than making // the operator wait for the periodic pass. if matches!(&result, Ok(Ok(_))) { let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { reconcile_cert_replication(cluster, secret).await; }); } match result { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "log": out })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/certs/{name}/renew — force renew. pub async fn certs_renew( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let result = web::block(move || crate::certbot::renew(&name)).await; // Renewal rotates the private key, so every replica is now stale. // The periodic reconcile would catch it within the interval anyway — // this just makes the UI-driven path feel immediate. if matches!(&result, Ok(Ok(_))) { let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { reconcile_cert_replication(cluster, secret).await; }); } match result { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "log": out })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// DELETE /api/certs/{name} — delete a cert. pub async fn certs_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let deleted_name = name.clone(); let result = web::block(move || crate::certbot::delete(&name)).await; // Drop it from the replicate list too. The reconcile's prune leg is // driven by that list (not by what's readable on disk), so leaving a // deleted cert in it would strand the replica on every peer forever // — and log a read failure every pass. if matches!(&result, Ok(Ok(_))) { let n = deleted_name.clone(); let dropped = web::block(move || { let mut cfg = crate::certbot::replication::ReplicationConfig::load(); if !cfg.is_replicated(&n) { return Ok::(false); } cfg.certs.retain(|c| c != &n); cfg.save().map(|_| true) }).await; match dropped { Ok(Ok(true)) => { tracing::info!( "cert replication: '{}' deleted — removed from replicate list, peers will prune", deleted_name ); let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { reconcile_cert_replication(cluster, secret).await; }); } Ok(Ok(false)) => {} Ok(Err(e)) => tracing::warn!("cert replication: config update after delete failed: {}", e), Err(e) => tracing::warn!("cert replication: config update after delete failed: {}", e), } } match result { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "log": out })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/certs/config — save certbot config (email, webroot, /// auto-renew toggle, reload_cmd override). Also regenerates the /// WolfProxy include snippet so the webroot path in nginx matches /// whatever certbot is about to write into. pub async fn certs_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = body.into_inner(); if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Best-effort — writing the snippet isn't fatal if /etc/wolfproxy // doesn't exist (WolfProxy may not be installed on this node). let _ = crate::certbot::write_nginx_snippet(&cfg); HttpResponse::Ok().json(serde_json::json!({ "saved": true, "nginx_snippet": crate::certbot::nginx_snippet_path().display().to_string(), })) } // ─── DNS Providers (for ACME DNS-01 + wildcard certs) ─────────────────── // // Lets the operator save one credentials INI per DNS API (Cloudflare, // Route53, etc.) at the cluster level, then issue wildcard certs // without ever touching port 80. See src/dns_providers/mod.rs for // storage + obfuscation; see crate::certbot::issue_via_provider for the // certbot invocation that consumes a stored provider. #[derive(Deserialize)] pub struct DnsProviderCreate { pub name: String, pub plugin: String, /// Multiline INI body the operator pasted in. Never logged. pub credentials: String, } #[derive(Deserialize)] pub struct DnsProviderUpdate { #[serde(default)] pub name: Option, /// Empty string ⇒ "leave creds alone". Optional so the UI can /// rename without re-pasting the secret. #[serde(default)] pub credentials: Option, } #[derive(Deserialize, Default)] pub struct DnsProviderTestRequest { /// Domain to use for the staging dry-run. Required — we don't /// guess the user's zone. UI defaults this to whatever was in the /// most recent cert request form. #[serde(default)] pub domain: String, /// Email for the staging-CA registration. Falls back to the saved /// `CertbotConfig.email` when empty. #[serde(default)] pub email: String, } /// GET /api/dns-providers — list providers (credentials redacted). pub async fn dns_providers_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let store = crate::dns_providers::DnsProviderStore::load(); HttpResponse::Ok().json(serde_json::json!({ "providers": store.list_redacted(), "known_plugins": crate::dns_providers::KNOWN_PLUGINS, })) } /// POST /api/dns-providers — add a new provider. Replicates the full /// store to every cluster peer so the provider is usable from any node /// (PapaSchlumpf 2026-05-17: "dns provider 'id' not found" when issuing /// a cert from a different node than the one the provider was added on). pub async fn dns_providers_add( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let body = body.into_inner(); let mut store = crate::dns_providers::DnsProviderStore::load(); let id = match store.add(body.name, body.plugin, &body.credentials) { Ok(id) => id, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let provider = store.get(&id).map(|p| p.redacted()); replicate_dns_providers_to_cluster(state.cluster.clone(), state.cluster_secret.clone(), store); HttpResponse::Ok().json(serde_json::json!({ "id": id, "provider": provider, })) } /// PUT /api/dns-providers/{id} — update name and/or credentials. pub async fn dns_providers_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let body = body.into_inner(); let mut store = crate::dns_providers::DnsProviderStore::load(); // Pass None when the field is missing entirely; pass Some(&str) // (which may be empty — store::update treats empty as "leave alone") // when the operator submitted the field. let creds = body.credentials.as_deref(); if let Err(e) = store.update(&id, body.name, creds) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let provider = store.get(&id).map(|p| p.redacted()); replicate_dns_providers_to_cluster(state.cluster.clone(), state.cluster_secret.clone(), store); HttpResponse::Ok().json(serde_json::json!({ "updated": true, "provider": provider, })) } /// DELETE /api/dns-providers/{id} — remove a provider and replicate the /// deletion to every peer. pub async fn dns_providers_remove( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut store = crate::dns_providers::DnsProviderStore::load(); if !store.remove(&id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("provider '{}' not found", id) })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } replicate_dns_providers_to_cluster(state.cluster.clone(), state.cluster_secret.clone(), store); HttpResponse::Ok().json(serde_json::json!({ "removed": true })) } /// POST /api/dns-providers/sync — peer-to-peer receiver. Accepts the /// sender's full DnsProviderStore and replaces the local store with it. /// Authenticated by `X-WolfStack-Secret` only (the operator never calls /// this directly — it's the fan-out target of `replicate_dns_providers_ /// to_cluster`). /// /// Replace-semantics (rather than merge) mirror the existing router /// config replication pattern (`networking/router/api.rs:: /// replicate_config_to_cluster`). The trade-off: if two operators add /// providers on different nodes concurrently, the second write wipes /// the first. v23.13 will move to a proper merge once we add per- /// provider timestamps and a tombstone log. pub async fn dns_providers_sync( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // Cluster-secret only — operators never call this. // // Was an inline `!= state.cluster_secret`, which had two problems. // It only compared the IN-MEMORY secret, so a peer authenticating // with the on-disk one was rejected and provider replication silently // stopped — reproducing the very "dns provider 'id' not found" this // endpoint exists to prevent. And `!=` on str is not constant time, // reintroducing the timing leak `validate_cluster_secret` was written // to close. The shared helper handles both. if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let incoming = body.into_inner(); if let Err(e) = incoming.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "applied": true, "count": incoming.providers.len(), })) } /// Push the current DnsProviderStore to every other cluster node so the /// list (and the obfuscated credentials with it — both ends share the /// same XOR key) stays in sync. Fired (in the background, doesn't block /// the originating user request) after every successful add/update/ /// remove. Mirrors `networking::router::api::replicate_config_to_cluster`. fn replicate_dns_providers_to_cluster( cluster: std::sync::Arc, cluster_secret: String, store: crate::dns_providers::DnsProviderStore, ) { tokio::spawn(async move { let nodes = cluster.get_all_nodes(); let self_id = crate::agent::self_node_id(); let body = match serde_json::to_string(&store) { Ok(b) => b, Err(e) => { tracing::warn!("dns-providers replicate: serialise failed: {}", e); return; } }; let client = &*API_HTTP_CLIENT; for node in nodes { if node.is_self || node.id == self_id { continue; } if !node.online { continue; } if node.node_type != "wolfstack" { continue; } let urls = build_node_urls(&node.address, node.port, "/api/dns-providers/sync"); let mut replicated = false; let mut last_err = String::new(); for url in &urls { match client.post(url) .peer_auth(&cluster_secret) .header("Content-Type", "application/json") .timeout(std::time::Duration::from_secs(10)) .body(body.clone()) .send().await { Ok(r) if r.status().is_success() => { tracing::debug!("dns-providers replicated to {} via {}", node.id, url); let _ = r.bytes().await; replicated = true; break; } Ok(r) => { last_err = format!("HTTP {} from {}", r.status(), url); let _ = r.bytes().await; } Err(e) => { last_err = format!("{} ({})", e, url); } } } if !replicated { // Loud — a silent replicate failure here is exactly what // PapaSchlumpf hit when the provider lived on one node // only. Log so the operator can see why peers are out of // sync rather than discovering it at cert-issue time. tracing::warn!("dns-providers replicate to {} ({}) FAILED — last error: {}", node.hostname, node.address, last_err); } } }); } /// GET /api/dns-providers/plugins — report which certbot DNS plugins /// are installed on THIS node, and for each missing one, the exact /// install command for this host's distro. /// /// This is the answer to klasSponsor's "certbot DNS not working on /// Debian trixie/Ubuntu" — works on Proxmox because Proxmox typically /// has the plugin packages pre-installed; plain Debian/Ubuntu doesn't. /// The endpoint runs in the wolfstack service context, so it sees /// the same view of installed plugins that certbot will see when /// issuing a certificate (no PATH / venv mismatch). pub async fn dns_providers_plugins(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let report = tokio::task::spawn_blocking(|| { let installed = crate::certbot::installed_plugins(); let container = crate::certbot::detect_container_kind(); // Compute the install command for every missing plugin in // ONE pass that batches the apt-cache / dnf probes — old // path did N×~50ms shellouts (one per plugin); new path is // a single ~50ms probe regardless of plugin count. let plugins = crate::certbot::preflight_all(&installed); let cache_status = crate::certbot::package_cache_status(); let snap_info = crate::certbot::snap_status(); serde_json::json!({ "certbot_installed": crate::certbot::is_installed(), "all_installed_plugins": installed, "plugins": plugins, "container_kind": container.label(), "package_cache_status": cache_status, "snap": snap_info, }) }) .await .unwrap_or_else(|e| serde_json::json!({ "error": format!("preflight failed: {}", e) })); HttpResponse::Ok().json(report) } /// POST /api/dns-providers/plugins/{plugin}/install — install the /// distro package (or pipx-inject) for the named DNS plugin. Runs /// the install command in the wolfstack service context (root), so it /// works identically in host / LXC container / Proxmox CT / VM / Docker /// — the only contexts that differ are snap-based ones, which we /// explicitly avoid in the install plan. pub async fn dns_providers_plugin_install( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let actor = match require_auth(&req, &state) { Ok(a) => a, Err(r) => return r }; let plugin = path.into_inner(); if !crate::dns_providers::is_known_plugin(&plugin) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown plugin '{}'", plugin) })); } let plugin_for_block = plugin.clone(); let result = tokio::task::spawn_blocking(move || { crate::certbot::install_plugin(&plugin_for_block) }).await; match result { Ok(Ok(log)) => { gateway_audit(&state, &actor, "info", "Installed certbot DNS plugin", &format!("dns-{}", plugin)); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "plugin": plugin, "log": log, })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "plugin": plugin, "error": e, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "plugin": plugin, "error": format!("install task failed: {}", e), })), } } /// POST /api/dns-providers/{id}/test — staging-CA dry-run to validate /// credentials. Stores the result on the provider entry so the UI can /// show "last tested OK 2 minutes ago" or surface the error. pub async fn dns_providers_test( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let body = body.into_inner(); let domain = body.domain.trim().to_string(); if domain.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a domain is required for the dry-run (e.g. example.com)" })); } let email = body.email.clone(); let id_for_block = id.clone(); let result = web::block(move || { crate::certbot::issue_via_provider( &[domain], &email, &id_for_block, true, // dry_run — Let's Encrypt staging ) }) .await; // Persist the result on the provider entry. The dry-run side of // certbot still uses staging-CA rate limits, so we want the UI to // remember "you already tested this 5 minutes ago — don't hammer". let (success, message): (bool, String) = match result { Ok(Ok(out)) => (true, truncate(&out, 240)), Ok(Err(e)) => (false, truncate(&e, 240)), Err(e) => (false, truncate(&e.to_string(), 240)), }; let mut store = crate::dns_providers::DnsProviderStore::load(); if let Some(p) = store.get_mut(&id) { p.last_tested_at = chrono::Utc::now().to_rfc3339(); p.last_test_result = if success { "ok".to_string() } else { message.clone() }; let _ = store.save(); } if success { HttpResponse::Ok().json(serde_json::json!({ "ok": true, "log": message })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": message })) } } fn truncate(s: &str, max: usize) -> String { if s.chars().count() <= max { return s.to_string(); } let cut: String = s.chars().take(max).collect(); format!("{}…", cut) } // ─── Cloud Providers (for edge LB / tunnel automation) ───────────────── // // Sister surface to DNS Providers. Holds infrastructure-side tokens // (Cloudflare account/API token for now; Hetzner/DigitalOcean in // v23.3+). Consumed by the edge reconcile loop in `crate::edge`. #[derive(Deserialize)] pub struct CloudProviderCreate { pub name: String, pub kind: String, // "cloudflare" — accepted set lives in edge::store pub credentials: String, // JSON object as a string; shape is per-kind } #[derive(Deserialize)] pub struct CloudProviderUpdate { #[serde(default)] pub name: Option, /// Optional new credentials. Empty string ⇒ leave alone. #[serde(default)] pub credentials: Option, } /// GET /api/edge/cloud-providers — redacted list. pub async fn cloud_providers_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let store = crate::edge::CloudProviderStore::load(); HttpResponse::Ok().json(serde_json::json!({ "providers": store.list_redacted(), // Keep the wire format symmetric with /api/dns-providers — UIs // can render the list of supported kinds without hard-coding. "supported_kinds": ["cloudflare"], })) } /// POST /api/edge/cloud-providers — add new credentials. pub async fn cloud_providers_add( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let body = body.into_inner(); let kind = match crate::edge::CloudProviderKind::from_str(&body.kind) { Some(k) => k, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unsupported kind '{}' — accepted: cloudflare", body.kind) })), }; let mut store = crate::edge::CloudProviderStore::load(); let id = match store.add(body.name, kind, &body.credentials) { Ok(id) => id, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let provider = store.get(&id).map(|p| p.redacted()); HttpResponse::Ok().json(serde_json::json!({ "id": id, "provider": provider })) } /// PUT /api/edge/cloud-providers/{id} — update name / credentials. pub async fn cloud_providers_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let body = body.into_inner(); let mut store = crate::edge::CloudProviderStore::load(); if let Err(e) = store.update(&id, body.name, body.credentials.as_deref()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "updated": true, "provider": store.get(&id).map(|p| p.redacted()), })) } /// DELETE /api/edge/cloud-providers/{id}. pub async fn cloud_providers_remove( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut store = crate::edge::CloudProviderStore::load(); if !store.remove(&id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("provider '{}' not found", id) })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "removed": true })) } /// POST /api/edge/cloud-providers/{id}/test — verify credentials by /// hitting the provider's API. For Cloudflare this lists zones with /// per_page=1 — cheap, free, and proves the token has at least /// `Zone:Read`. pub async fn cloud_providers_test( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let store = crate::edge::CloudProviderStore::load(); let provider = match store.get(&id) { Some(p) => p, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("provider '{}' not found", id) })), }; let kind = provider.kind; let creds = match store.credentials_json(&id) { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let (success, message) = match kind { crate::edge::CloudProviderKind::Cloudflare => { match crate::edge::cloudflare::CloudflareCreds::from_value(&creds) { Ok(cf) => match crate::edge::cloudflare::ping(&cf).await { Ok(_) => (true, "ok".to_string()), Err(e) => (false, truncate(&e, 240)), }, Err(e) => (false, e), } } crate::edge::CloudProviderKind::Hetzner => { // Hetzner cloud token — verify against the Cloud LB API // (cheapest endpoint that proves the token is valid). match crate::edge::hetzner_lb::HetznerCloudCreds::from_value(&creds) { Ok(hc) => match crate::edge::hetzner_lb::ping(&hc).await { Ok(_) => (true, "ok".to_string()), Err(e) => (false, truncate(&e, 240)), }, Err(e) => (false, e), } } crate::edge::CloudProviderKind::DigitalOcean => { // DO token works for both LB and DNS; we verify with the // domains list since both surfaces require the same scope. match crate::edge::digitalocean_dns::DigitalOceanCreds::from_value(&creds) { Ok(d) => match crate::edge::digitalocean_dns::ping(&d).await { Ok(_) => (true, "ok".to_string()), Err(e) => (false, truncate(&e, 240)), }, Err(e) => (false, e), } } }; // Persist the result back onto the entry so the UI badge survives // a page reload. let mut store2 = crate::edge::CloudProviderStore::load(); if let Some(p) = store2.get_mut(&id) { p.last_verified_at = chrono::Utc::now().to_rfc3339(); p.last_verify_result = if success { "ok".to_string() } else { message.clone() }; let _ = store2.save(); } if success { HttpResponse::Ok().json(serde_json::json!({ "ok": true, "log": message })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": message })) } } /// POST /api/edge/cloudflare-tunnel/install/{proxy_id} — install /// `cloudflared` as a systemd service on the LOCAL node using the /// connector token of the proxy's tunnel. Runs once per node — the /// frontend fans out across `proxy.targets` via the cluster proxy /// so each node ends up running cloudflared. /// /// We look up the proxy via the router config rather than taking the /// tunnel name + creds from the URL — that way the tunnel-token /// fetch authenticates against the operator's cloud provider entry /// (already audited at save time), and there's no way for a caller /// to ask us to install cloudflared against an arbitrary token. pub async fn cloudflare_tunnel_install( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let proxy_id = path.into_inner(); // Resolve proxy → tunnel name + cloud provider id. let (tunnel_name, cloud_provider_id) = { let cfg = state.router.config.read().unwrap(); let p = match cfg.http_proxies.iter().find(|p| p.id == proxy_id) { Some(p) => p, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("HTTP proxy '{}' not found", proxy_id) })), }; match &p.edge { crate::edge::EdgeStrategy::CloudflareTunnel { cloud_provider_id, tunnel_name, .. } => { (tunnel_name.clone(), cloud_provider_id.clone()) } other => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!( "proxy '{}' edge is '{}', not cloudflare_tunnel — install only applies to tunnel proxies", proxy_id, other.kind() ) })), } }; // Load creds, find the tunnel, fetch its connector token. let providers = crate::edge::CloudProviderStore::load(); let provider = match providers.get(&cloud_provider_id) { Some(p) => p, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("cloud provider '{}' not found — re-pick it on the proxy", cloud_provider_id) })), }; if provider.kind != crate::edge::CloudProviderKind::Cloudflare { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("cloud provider '{}' is kind {} — tunnel install needs a Cloudflare provider", provider.name, provider.kind.label()) })); } let creds_val = match providers.credentials_json(&cloud_provider_id) { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let creds = match crate::edge::cloudflare_tunnel::CloudflareTunnelCreds::from_value(&creds_val) { Ok(c) => c, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let tunnel = match crate::edge::reconcile::find_tunnel_by_name(&creds, &tunnel_name).await { Ok(Some(t)) => t, Ok(None) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("tunnel '{}' not found in Cloudflare account — save the proxy first to create it", tunnel_name) })), Err(e) => return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("lookup tunnel: {}", e) })), }; let token = match crate::edge::cloudflare_tunnel::get_tunnel_token(&creds, &tunnel.id).await { Ok(t) => t, Err(e) => return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("fetch tunnel token: {}", e) })), }; // Shell out to cloudflared on a blocking thread — token contains // only base64url chars, but install_cloudflared_service re-validates // before exec'ing. let result = actix_web::web::block(move || { crate::edge::cloudflare_tunnel::install_cloudflared_service(&token) }).await; match result { Ok(Ok(log)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "tunnel_id": tunnel.id, "log": log, })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "ok": false, "tunnel_id": tunnel.id, "error": e, })), Err(join) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("install task failed: {}", join) })), } } // ─── GitHub Backup ────────────────────────────────────────────────────── /// GET /api/github-backup/config — returns the config with the token /// masked to `••••••••XXXX`. UI uses this to pre-fill the form without /// the real token ever reaching the browser. pub async fn github_backup_config_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::github_backup::GithubBackupConfig::load().masked()) } /// POST /api/github-backup/config — save the config. If the token /// field is empty or starts with `••••` the existing stored token is /// kept, so admins can edit other fields without re-pasting the token. pub async fn github_backup_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut incoming = body.into_inner(); if incoming.token.trim().is_empty() || incoming.token.starts_with('•') { let existing = crate::github_backup::GithubBackupConfig::load(); incoming.token = existing.token; } if let Err(e) = incoming.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(incoming.masked()) } /// POST /api/github-backup/push — run a full backup push now and /// return the new commit sha (or an error). pub async fn github_backup_push_now(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::github_backup::push_all().await { Ok(sha) => HttpResponse::Ok().json(serde_json::json!({ "message": "Pushed to GitHub", "commit_sha": sha, })), Err(e) => { // Best-effort: record the error on the config so the UI // status line can show what went wrong without the user // having to keep the toast visible. let mut cfg = crate::github_backup::GithubBackupConfig::load(); cfg.last_push_error = Some(e.clone()); let _ = cfg.save(); HttpResponse::BadRequest().json(serde_json::json!({ "error": e })) } } } /// POST /api/github-backup/restore — pull latest from the configured /// branch and overwrite tracked files in /etc/wolfstack/. /// Destructive; the frontend gates this behind the typed-YES modal. pub async fn github_backup_restore(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::github_backup::restore_all().await { Ok(count) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Restored {} files from GitHub", count), "files_restored": count, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/github-backup/test — verify the token + repo + branch /// work before an admin tries to push. Returns the authenticated /// GitHub user and whether the configured branch exists. pub async fn github_backup_test(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::github_backup::test_credentials().await { Ok(info) => HttpResponse::Ok().json(info), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── Dashboard Sync ───────────────────────────────────────────────────── // // Operator picks target nodes in the UI, hits "Push now", and the // curated config bundle ships to those peers via X-WolfStack-Secret. // No on-write replication, no pull. See src/dashboard_sync/mod.rs for // the bundle definition and apply logic. /// GET /api/dashboard-sync/targets — current target list, the file /// bundle the UI should display under "what gets pushed", and the /// last-push outcome per target. pub async fn dashboard_sync_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = crate::dashboard_sync::DashboardSyncConfig::load(); HttpResponse::Ok().json(serde_json::json!({ "targets": cfg.targets, "last_push": cfg.last_push, "bundle_files": crate::dashboard_sync::BUNDLE_FILES, "self_node": state.cluster.self_id.clone(), })) } /// POST /api/dashboard-sync/targets — replace the target list. Body: /// `{ "targets": ["node-id", ...] }`. Self-id is silently filtered out /// — pushing to ourselves is a no-op that would only confuse the UI. pub async fn dashboard_sync_save_targets( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let raw: Vec = body.get("targets") .and_then(|v| v.as_array()) .map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()) .unwrap_or_default(); // Dedupe, drop self-id, and keep order stable so the UI tree // renders predictably across reloads. let self_id = state.cluster.self_id.clone(); let mut seen = std::collections::HashSet::new(); let targets: Vec = raw.into_iter() .filter(|id| id != &self_id && seen.insert(id.clone())) .collect(); let mut cfg = crate::dashboard_sync::DashboardSyncConfig::load(); cfg.targets = targets; if let Err(e) = cfg.save() { return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("save failed: {}", e) })); } HttpResponse::Ok().json(serde_json::json!({ "targets": cfg.targets })) } /// POST /api/dashboard-sync/push — build the bundle on this node and /// fan it out to every target in the saved list. Returns a per-target /// outcome map; the same map is persisted so the UI can show "last /// pushed X ago" without a fresh attempt. pub async fn dashboard_sync_push(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut cfg = crate::dashboard_sync::DashboardSyncConfig::load(); if cfg.targets.is_empty() { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "no targets selected" })); } // Build once, send many. base64 lets us reuse the encoded body // for every peer without re-encoding per call. let self_id = state.cluster.self_id.clone(); let bundle = crate::dashboard_sync::build_bundle(); let file_count = bundle.len(); let payload = crate::dashboard_sync::encode_payload(self_id.clone(), bundle); let body = match serde_json::to_vec(&payload) { Ok(b) => b, Err(e) => return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("serialise: {}", e) })), }; let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); // Resolve target IDs to addresses up front so we can record an // outcome even for targets the cluster has never heard of (the // operator may have pasted a stale id, or the peer hasn't // checked in yet). let mut futures = Vec::with_capacity(cfg.targets.len()); for target_id in &cfg.targets { let target_id = target_id.clone(); let node = nodes.iter().find(|n| n.id == target_id).cloned(); let secret = secret.clone(); let client = client.clone(); let body = body.clone(); futures.push(async move { let Some(node) = node else { return (target_id, crate::dashboard_sync::PushOutcome { at: now, ok: false, files: 0, error: Some("node not found in cluster".into()), }); }; if !node.online { return (target_id, crate::dashboard_sync::PushOutcome { at: now, ok: false, files: 0, error: Some("node offline".into()), }); } let urls = build_node_urls(&node.address, node.port, "/api/dashboard-sync/receive"); let mut last_err = String::new(); for url in &urls { let res = client.post(url) .peer_auth(&secret) .header("Content-Type", "application/json") .timeout(std::time::Duration::from_secs(60)) .body(body.clone()) .send().await; match res { Ok(r) if r.status().is_success() => { // Receiver reports a file count — use that, not // the count we sent, so a target running an // older build that allowlists fewer files is // visible to the operator. let txt = r.text().await.unwrap_or_default(); let n = serde_json::from_str::(&txt) .ok() .and_then(|v| v.get("files").and_then(|f| f.as_u64())) .unwrap_or(file_count as u64) as u32; return (target_id, crate::dashboard_sync::PushOutcome { at: now, ok: true, files: n, error: None, }); } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); last_err = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(|s| s.to_string())) .unwrap_or_else(|| format!("HTTP {}", status)); } Err(e) => last_err = format!("{}", e), } } (target_id, crate::dashboard_sync::PushOutcome { at: now, ok: false, files: 0, error: Some(if last_err.is_empty() { "unreachable".into() } else { last_err }), }) }); } let results: Vec<(String, crate::dashboard_sync::PushOutcome)> = futures::future::join_all(futures).await; for (id, outcome) in &results { cfg.last_push.insert(id.clone(), outcome.clone()); } if let Err(e) = cfg.save() { tracing::warn!("dashboard-sync: failed to persist last_push: {}", e); } let outcomes: std::collections::HashMap = results.into_iter().collect(); HttpResponse::Ok().json(serde_json::json!({ "outcomes": outcomes, "bundle_files": file_count, })) } /// POST /api/dashboard-sync/receive — peer endpoint. Auth: cluster /// secret only (no session). Validates filenames against the bundle /// allowlist on this node and writes files via paths::write_secure. /// /// Takes the body as `web::Bytes` instead of `web::Json<…>` because /// actix-web's JSON extractor caps at 32 KB by default and a real /// bundle is hundreds of KB or more. The 2 GB `PayloadConfig` set in /// `main.rs` covers raw-bytes extractors like this one. pub async fn dashboard_sync_receive( req: HttpRequest, state: web::Data, body: web::Bytes, ) -> HttpResponse { // Cluster-secret-only: this endpoint mutates on-disk config under // /etc/wolfstack/, so we deliberately do NOT accept session-cookie // or API-key auth. Only a peer with the cluster secret can push. if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let payload: crate::dashboard_sync::PushPayload = match serde_json::from_slice(&body) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest() .json(serde_json::json!({ "error": format!("decode payload: {}", e) })), }; match crate::dashboard_sync::apply_bundle(&payload) { Ok(n) => { tracing::info!("dashboard-sync: applied {} files from peer '{}'", n, payload.from_node); HttpResponse::Ok().json(serde_json::json!({ "files": n, "from_node": payload.from_node, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── Control Panel (cluster-wide apps view) ───────────────────────────── /// GET /api/control-panel/inventory — every VM, LXC and Docker container /// across every reachable cluster node, flattened into a single list. /// Fans out in parallel to each node's per-kind listing endpoints using /// the cluster secret; unreachable nodes are skipped with a diagnostic /// entry in the response so the UI can surface per-node failures. pub async fn control_panel_inventory(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); // Aggregate every reachable node this WolfStack knows about — // across every `cluster_name` label in the dashboard. All nodes // in `state.cluster` are peers that share the cluster_secret, so // authentication to any of them works with our local secret. // The only filter is reachability (either self or recently // heartbeat-ed online within 5 minutes). // // No cluster-name filter: the `cluster_name` field is a user // label for sidebar grouping, not a security boundary. Filtering // by it was dropping peer nodes that happened to live under a // different display label. let nodes: Vec<_> = state.cluster.get_all_nodes() .into_iter() .filter(|n| n.is_self || (n.online && now.saturating_sub(n.last_seen) < 300)) .collect(); let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let mut items: Vec = Vec::new(); let mut node_errors: Vec = Vec::new(); for node in &nodes { let (mut n_items, mut n_errs) = fetch_one_node_inventory(&state, client, node, &secret).await; items.append(&mut n_items); node_errors.append(&mut n_errs); } HttpResponse::Ok().json(serde_json::json!({ "items": items, "errors": node_errors, "generated_at": now, })) } /// Per-node inventory fetch — Docker/LXC/native-VM plus Proxmox guests for /// PVE-registered nodes. Extracted so the aggregate endpoint and the /// per-node lazy-load endpoint share the same shaping + error handling. async fn fetch_one_node_inventory( state: &web::Data, client: &reqwest::Client, node: &crate::agent::Node, secret: &str, ) -> (Vec, Vec) { let cluster_name = node.cluster_name.clone() .or(node.pve_cluster_name.clone()) .unwrap_or_else(|| "WolfStack".to_string()); let base_entry = serde_json::json!({ "node_id": node.id, "node_hostname": node.hostname, "cluster": cluster_name, }); let mut items: Vec = Vec::new(); let mut errors: Vec = Vec::new(); let endpoints = [ ("docker", "/api/containers/docker"), ("lxc", "/api/containers/lxc"), ("vm", "/api/vms"), ("share", "/api/gateways"), ]; let is_wolfstack_node = node.node_type == "wolfstack" || node.node_type.is_empty(); for (kind, path) in &endpoints { if !is_wolfstack_node { continue; } let raw: Option = if node.is_self { fetch_local_json(state, path).await } else { fetch_remote_json(client, &node.address, node.port, path, secret).await }; let Some(raw) = raw else { // /api/gateways doesn't exist on older WolfStack peers — treat // as "no shares" rather than a hard error. if *kind != "share" { errors.push(serde_json::json!({ "node_id": node.id, "node_hostname": node.hostname, "kind": kind, "error": "unreachable or endpoint failed", })); } continue; }; let arr = raw.as_array().cloned().unwrap_or_default(); for entry in arr { if *kind == "share" { items.push(shape_share_item(&base_entry, &entry)); } else { items.push(shape_inventory_item(&base_entry, kind, &entry)); } } } if node.node_type == "proxmox" { let token = node.pve_token.clone().unwrap_or_default(); let pve_name = node.pve_node_name.clone().unwrap_or_default(); let fp = node.pve_fingerprint.as_deref(); if !token.is_empty() && !pve_name.is_empty() { let pve_client = crate::proxmox::PveClient::new(&node.address, node.port, &token, fp, &pve_name); match pve_client.list_all_guests().await { Ok(guests) => { if let Ok(val) = serde_json::to_value(&guests) && let Some(arr) = val.as_array() { for g in arr { items.push(shape_pve_item(&base_entry, g)); } } } Err(e) => errors.push(serde_json::json!({ "node_id": node.id, "node_hostname": node.hostname, "kind": "pve", "error": e, })), } } } (items, errors) } /// GET /api/control-panel/nodes — reachable peers the inventory will be /// fetched from. Returned up-front so the frontend can paint per-node /// "Loading…" placeholders and then fire parallel per-node requests. pub async fn control_panel_nodes(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let nodes: Vec = state.cluster.get_all_nodes() .into_iter() .filter(|n| n.is_self || (n.online && now.saturating_sub(n.last_seen) < 300)) .map(|n| { let cluster_name = n.cluster_name.clone() .or(n.pve_cluster_name.clone()) .unwrap_or_else(|| "WolfStack".to_string()); serde_json::json!({ "id": n.id, "hostname": n.hostname, "cluster": cluster_name, "node_type": n.node_type, "is_self": n.is_self, }) }) .collect(); HttpResponse::Ok().json(serde_json::json!({ "nodes": nodes })) } /// GET /api/control-panel/inventory/node/{id} — inventory for one node. /// Fans out to just that node's listing endpoints; returns the same /// `{items, errors}` shape as the aggregate endpoint so the frontend /// can merge responses without special-casing. pub async fn control_panel_inventory_node( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let Some(node) = state.cluster.get_node(&id) else { return HttpResponse::NotFound().json(serde_json::json!({"error": "node not found"})); }; let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let (items, errors) = fetch_one_node_inventory(&state, client, &node, &secret).await; HttpResponse::Ok().json(serde_json::json!({ "node_id": node.id, "items": items, "errors": errors, })) } async fn fetch_local_json(state: &web::Data, path: &str) -> Option { // Try the loopback candidates in order rather than picking one port up // front. The previous version assumed that "TLS is on" implies the plain // inter-node listener exists, but a node with a CA-signed certificate // never binds it (`cert_is_self_signed` in main.rs), so on those nodes // every self-fetch failed — the node silently contributed nothing to its // own inventory. See `ports::self_api_urls`. let client = &*API_HTTP_CLIENT; for url in crate::ports::self_api_urls(path) { let Ok(resp) = client.get(&url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(state.cluster_secret.clone()) .send().await else { continue; // wrong scheme or nothing bound here — try the next }; if resp.status().is_success() { if let Ok(j) = resp.json::().await { return Some(j); } // json() failing still consumed the body. return None; } // A bound listener that gave a definitive non-2xx answer is the right // listener — a different port won't answer differently. Drain the body // so the socket returns to the keep-alive pool, then stop. let _ = resp.bytes().await; return None; } None } async fn fetch_remote_json( client: &reqwest::Client, address: &str, port: u16, path: &str, secret: &str, ) -> Option { let urls = build_node_urls(address, port, path); for url in &urls { if let Ok(resp) = client.get(url) .peer_auth(secret) .timeout(std::time::Duration::from_secs(5)) .send().await { if resp.status().is_success() { if let Ok(j) = resp.json::().await { return Some(j); } // json() failing still consumed the body. } else { // Non-success: drain the body so the connection // returns to the keep-alive pool. Previously this // dropped `resp` unread, preventing reuse. let _ = resp.bytes().await; } } } None } /// Normalise a per-node Docker/LXC/VM entry into the flat InventoryItem shape. fn shape_inventory_item(base: &serde_json::Value, kind: &str, entry: &serde_json::Value) -> serde_json::Value { let name = entry.get("name").and_then(|v| v.as_str()) .or_else(|| entry.get("id").and_then(|v| v.as_str())) .unwrap_or("").to_string(); let raw_status = match kind { "vm" => if entry.get("running").and_then(|v| v.as_bool()).unwrap_or(false) { "running" } else { "stopped" }.to_string(), _ => entry.get("status").and_then(|v| v.as_str()) .or_else(|| entry.get("state").and_then(|v| v.as_str())) .unwrap_or("unknown").to_string(), }; // Docker returns human-friendly strings like "Up 2 hours" or // "Exited (0) 5 minutes ago" in the `status` field, and terse ones // like "running" in `state`. Normalise both forms to the five // buckets the UI knows how to colour: running / stopped / paused // / unknown. Anything that looks alive → running; anything that // looks dead → stopped. let lc = raw_status.to_lowercase(); let status = if lc.contains("pause") { "paused" } else if lc.starts_with("up ") || lc == "up" || lc.contains("running") || lc.contains("restart") { "running" } else if lc.contains("exit") || lc.contains("stop") || lc.contains("dead") || lc.contains("created") { "stopped" } else { "unknown" }; let image = entry.get("image").and_then(|v| v.as_str()).unwrap_or("").to_string(); let cpu = entry.get("cpu_percent").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32; let mem = entry.get("memory_usage").and_then(|v| v.as_u64()) .or_else(|| entry.get("memory_mb").and_then(|v| v.as_u64()).map(|mb| mb * 1024 * 1024)) .unwrap_or(0); let mem_limit = entry.get("memory_limit").and_then(|v| v.as_u64()).unwrap_or(0); serde_json::json!({ "node_id": base.get("node_id"), "node_hostname": base.get("node_hostname"), "cluster": base.get("cluster"), "kind": kind, "name": name, "status": status.to_lowercase(), "image": image, "cpu_percent": cpu, "memory_bytes": mem, "memory_limit_bytes": mem_limit, }) } /// Normalise a WolfStack Gateway into the flat InventoryItem shape. /// Status maps from runtime: serving+healthy → running; serving but /// unhealthy → unknown; disabled or no runtime → stopped. fn shape_share_item(base: &serde_json::Value, entry: &serde_json::Value) -> serde_json::Value { let name = entry.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(); let id = entry.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string(); let disabled = entry.get("disabled").and_then(|v| v.as_bool()).unwrap_or(false); let runtime = entry.get("runtime"); let serving = runtime.and_then(|r| r.get("serving")).and_then(|v| v.as_bool()).unwrap_or(false); let healthy = runtime.and_then(|r| r.get("healthy")).and_then(|v| v.as_bool()).unwrap_or(false); let status = if disabled { "stopped" } else if serving && healthy { "running" } else if serving { "unknown" } else { "stopped" }; let protocols = entry.get("protocols").cloned().unwrap_or(serde_json::json!([])); let tier = entry.get("performance_tier").and_then(|v| v.as_str()).unwrap_or("").to_string(); let sessions = runtime.and_then(|r| r.get("active_sessions")).and_then(|v| v.as_u64()).unwrap_or(0); serde_json::json!({ "node_id": base.get("node_id"), "node_hostname": base.get("node_hostname"), "cluster": base.get("cluster"), "kind": "share", "name": name, "status": status, "image": format!("{} · tier:{}", protocols_label(&protocols), tier), "cpu_percent": 0.0, "memory_bytes": 0u64, "memory_limit_bytes": 0u64, "share_id": id, "share_protocols": protocols, "share_sessions": sessions, "share_tier": tier, }) } fn protocols_label(p: &serde_json::Value) -> String { if let Some(arr) = p.as_array() { arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_uppercase()).collect::>().join("+") } else { String::new() } } /// Normalise a Proxmox PveGuest into the flat InventoryItem shape. /// `pve: true` + `vmid` are carried through so the frontend can route /// actions to the Proxmox-specific endpoint (`/api/nodes/{id}/pve/{vmid}/{action}`) /// instead of the WolfStack Docker/LXC ones which don't exist on a /// Proxmox node. fn shape_pve_item(base: &serde_json::Value, g: &serde_json::Value) -> serde_json::Value { let name = g.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(); let status = g.get("status").and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); let guest_type = g.get("guest_type").and_then(|v| v.as_str()).unwrap_or("vm"); let kind = if guest_type.eq_ignore_ascii_case("lxc") { "lxc" } else { "vm" }; let vmid = g.get("vmid").and_then(|v| v.as_u64()).unwrap_or(0); let cpu = g.get("cpu").and_then(|v| v.as_f64()).map(|f| (f * 100.0) as f32).unwrap_or(0.0); let mem = g.get("mem").and_then(|v| v.as_u64()).unwrap_or(0); let mem_limit = g.get("maxmem").and_then(|v| v.as_u64()).unwrap_or(0); serde_json::json!({ "node_id": base.get("node_id"), "node_hostname": base.get("node_hostname"), "cluster": base.get("cluster"), "kind": kind, "name": name, "status": status.to_lowercase(), "image": "", "cpu_percent": cpu, "memory_bytes": mem, "memory_limit_bytes": mem_limit, "pve": true, "vmid": vmid, }) } /// GET /api/control-panel/groups — user-defined Custom groups. pub async fn control_panel_groups_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::control_panel::ControlPanelConfig::load()) } /// POST /api/control-panel/groups — create a new group. Body: { name, colour? }. pub async fn control_panel_groups_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); if name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "name required"})); } let colour = body.get("colour").and_then(|v| v.as_str()).unwrap_or("#3b82f6").to_string(); let _guard = crate::control_panel::CONFIG_LOCK.lock().unwrap(); let mut cfg = crate::control_panel::ControlPanelConfig::load(); let id = format!("grp-{}", uuid::Uuid::new_v4().simple()); let order = cfg.groups.iter().map(|g| g.order).max().unwrap_or(0) + 1; let group = crate::control_panel::Group { id, name, colour, order, members: Vec::new() }; cfg.groups.push(group.clone()); if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(group) } /// PUT /api/control-panel/groups/{id} — rename, recolour, or reorder a group. pub async fn control_panel_groups_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let _guard = crate::control_panel::CONFIG_LOCK.lock().unwrap(); let mut cfg = crate::control_panel::ControlPanelConfig::load(); let Some(group) = cfg.groups.iter_mut().find(|g| g.id == id) else { return HttpResponse::NotFound().json(serde_json::json!({"error": "group not found"})); }; if let Some(n) = body.get("name").and_then(|v| v.as_str()) { let trimmed = n.trim(); if !trimmed.is_empty() { group.name = trimmed.to_string(); } } if let Some(c) = body.get("colour").and_then(|v| v.as_str()) { group.colour = c.to_string(); } if let Some(o) = body.get("order").and_then(|v| v.as_i64()) { group.order = o as i32; } let updated = group.clone(); if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(updated) } /// DELETE /api/control-panel/groups/{id} pub async fn control_panel_groups_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let _guard = crate::control_panel::CONFIG_LOCK.lock().unwrap(); let mut cfg = crate::control_panel::ControlPanelConfig::load(); let before = cfg.groups.len(); cfg.groups.retain(|g| g.id != id); if cfg.groups.len() == before { return HttpResponse::NotFound().json(serde_json::json!({"error": "group not found"})); } if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(serde_json::json!({"deleted": true})) } /// POST /api/control-panel/groups/{id}/members — replace the member /// list for a group. Body: `{ members: [{ node_id, kind, name }, ...] }`. /// Replaces the whole set atomically; simpler than incremental add/remove /// endpoints and matches the UI pattern of persisting after each drag. pub async fn control_panel_groups_set_members( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let members_val = body.get("members").cloned().unwrap_or(serde_json::Value::Null); let members: Vec = serde_json::from_value(members_val) .unwrap_or_default(); let _guard = crate::control_panel::CONFIG_LOCK.lock().unwrap(); let mut cfg = crate::control_panel::ControlPanelConfig::load(); let Some(group) = cfg.groups.iter_mut().find(|g| g.id == id) else { return HttpResponse::NotFound().json(serde_json::json!({"error": "group not found"})); }; group.members = members; let updated = group.clone(); if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } HttpResponse::Ok().json(updated) } // ─── Cluster Services Discovery ───────────────────────────────────────── /// GET /api/cluster-services — every web service this user can see: /// the cluster-wide auto-discovered list + their own pinned manual URLs. /// Other users' pinned URLs are not returned. pub async fn cluster_services_list(req: HttpRequest, state: web::Data) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; HttpResponse::Ok().json(serde_json::json!({ "services": crate::services_discovery::list_for_user(&user), "grouped": crate::services_discovery::grouped_for(&user), })) } /// POST /api/cluster-services/sweep — run a fresh discovery scan now. /// Discovery is on-demand (no periodic loop), so the page calls this /// when it loads. Returns once the sweep has finished, with the new /// merged list for the requesting user. pub async fn cluster_services_sweep(req: HttpRequest, state: web::Data) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let _ = tokio::task::spawn_blocking(crate::services_discovery::run_sweep).await; HttpResponse::Ok().json(serde_json::json!({ "ok": true, "services": crate::services_discovery::list_for_user(&user), "grouped": crate::services_discovery::grouped_for(&user), })) } #[derive(Deserialize)] pub struct AddManualServiceRequest { pub name: String, pub url: String, #[serde(default)] pub icon: String, #[serde(default = "default_other_category")] pub category: String, } fn default_other_category() -> String { "Other".to_string() } /// POST /api/cluster-services/manual — pin a service against the /// requesting user. Other users won't see this entry. pub async fn cluster_services_add_manual( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; match crate::services_discovery::add_manual_for_user( &user, body.name.clone(), body.url.clone(), body.icon.clone(), body.category.clone(), ) { Ok(svc) => HttpResponse::Ok().json(svc), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } pub async fn cluster_services_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let id = path.into_inner(); if crate::services_discovery::remove_manual_for_user(&user, &id) { HttpResponse::Ok().json(serde_json::json!({"removed": true})) } else { HttpResponse::NotFound().json(serde_json::json!({"error": "not found in your pinned list"})) } } // ─── Cluster Browser Sessions ─────────────────────────────────────────── /// GET /api/cluster-browser/sessions — active browser sessions from all nodes in the cluster. pub async fn cluster_browser_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut sessions = crate::cluster_browser::list_sessions(); // Try to fetch sessions from all remote nodes (timeout per node) let nodes: Vec<_> = state.cluster.nodes_read() .values() .filter(|n| !n.is_self && n.online) .cloned() .collect(); let client = &*API_HTTP_CLIENT; for node in nodes { let urls = build_node_urls(&node.address, node.port, "/api/cluster-browser/sessions"); for url in urls { match client .get(&url) .peer_auth(state.cluster_secret.clone()) .timeout(std::time::Duration::from_secs(3)) .send() .await { Ok(resp) => { if let Ok(bytes) = resp.bytes().await && let Ok(remote_sessions) = serde_json::from_slice::>(&bytes) { sessions.extend(remote_sessions); } break; // Got a response, don't try other URLs for this node } Err(_) => continue, // Try next URL } } } HttpResponse::Ok().json(sessions) } #[derive(Deserialize)] pub struct StartBrowserRequest { /// Optional override for the homepage URL the in-container Firefox /// loads at startup. Defaults to /cluster-home on this node. #[serde(default)] pub homepage: Option, } /// POST /api/cluster-browser/sessions — start a new browser session, /// returning the session metadata + the connect URL for the user. pub async fn cluster_browser_start( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; // Default homepage = our /cluster-home reachable from inside the // browser container. Two cases: // // - Docker backend: bridge containers can't reach 127.0.0.1 / the // host's wolfnet0 IP, so we use `host.docker.internal` — wired // up via `--add-host=host.docker.internal:host-gateway` in // spawn_container. Resolves to the bridge gateway; the host // listens there for any 0.0.0.0-bound service. // // - Kubernetes backend: pods have no host-gateway alias and // `host.docker.internal` doesn't resolve. Pods CAN reach the // node's IP directly via the cluster network, so we use // self_address (this WolfStack daemon's own IP). // // Plain HTTP regardless of WolfStack's TLS mode: a fresh Firefox // profile rejects self-signed certs, and the inter_node port is // always plain HTTP on TLS installs. let port_cfg = crate::ports::PortConfig::load(); let homepage_port = if state.tls_enabled { port_cfg.inter_node } else { port_cfg.api }; let homepage_host = if crate::cluster_browser::detect_local_kube().is_some() { state.cluster.self_address.clone() } else { "host.docker.internal".to_string() }; // Embed the user as a query param so /cluster-home renders that // user's pinned URLs alongside the cluster-wide discovered list. let default_homepage = format!( "http://{}:{}/cluster-home?user={}", crate::netaddr::bracket_host(&homepage_host), homepage_port, urlencoding_simple(&user) ); let homepage = body.homepage.clone().filter(|s| !s.trim().is_empty()).unwrap_or(default_homepage); let tls = state.tls_enabled; // Capture the host:port the client used to reach WolfStack BEFORE // spawn_blocking — connection_info() returns a borrow that can't // cross the await. This becomes the base of the proxy URL so the // browser's ws/wss goes back to WolfStack on the same port the // user is already connected to. let wolfstack_authority = req.connection_info().host().to_string(); let wolfstack_scheme = if state.tls_enabled { "https" } else { "http" }; let result = tokio::task::spawn_blocking(move || { crate::cluster_browser::start_session(&user, &homepage, tls) }).await; match result { Ok(Ok(session)) => HttpResponse::Ok().json(serde_json::json!({ "session": session, "connect_url": format!( "{}://{}/api/cluster-browser/session/{}/", wolfstack_scheme, wolfstack_authority, session.id ), })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e.to_string()})), } } /// GET /api/cluster-browser/image-status — quick "is the browser image /// pre-pulled on this node?" so the UI can show "First run will download /// ~700 MB" if not. pub async fn cluster_browser_image_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(serde_json::json!({ "image_present": crate::cluster_browser::image_present(), })) } /// POST /api/cluster-browser/sessions/start-stream — same as /sessions /// but streams `docker pull` progress (image download, layers, container /// start) as Server-Sent Events so the user has visible feedback during /// the multi-minute first-time pull instead of a silent spinner. /// Final event: `[done] {json}` with the connect_url. pub async fn cluster_browser_start_stream( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; // Homepage host: host.docker.internal for the Docker backend // (wired up via --add-host), self_address for the Kubernetes // backend (pods can reach the node's IP directly). See // cluster_browser_start for the full rationale. let port_cfg = crate::ports::PortConfig::load(); let homepage_port = if state.tls_enabled { port_cfg.inter_node } else { port_cfg.api }; let homepage_host = if crate::cluster_browser::detect_local_kube().is_some() { state.cluster.self_address.clone() } else { "host.docker.internal".to_string() }; // Embed the user as a query param so /cluster-home renders that // user's pinned URLs alongside the cluster-wide discovered list. let default_homepage = format!( "http://{}:{}/cluster-home?user={}", crate::netaddr::bracket_host(&homepage_host), homepage_port, urlencoding_simple(&user) ); let homepage = body.homepage.clone().filter(|s| !s.trim().is_empty()).unwrap_or(default_homepage); let tls = state.tls_enabled; // Capture the host:port and scheme the client used to reach // WolfStack BEFORE the blocking thread spawn — connection_info() // borrows from req which is !Send across the thread boundary. // Connect URL points to the in-process reverse proxy, not a // per-session port, so ws/wss rides whatever port WolfStack is on. let wolfstack_authority = req.connection_info().host().to_string(); let wolfstack_scheme = if state.tls_enabled { "https" } else { "http" }; let (std_tx, std_rx) = std::sync::mpsc::channel::(); let (tok_tx, mut tok_rx) = tokio::sync::mpsc::channel::(256); std::thread::spawn(move || { let result = crate::cluster_browser::start_session_streamed(&user, &homepage, tls, std_tx.clone()); match result { Ok(session) => { let payload = serde_json::json!({ "session": session, "connect_url": format!( "{}://{}/api/cluster-browser/session/{}/", wolfstack_scheme, wolfstack_authority, session.id ), }); let _ = std_tx.send(format!("[done] {}", payload)); } Err(e) => { let _ = std_tx.send(format!("[error] {}", e)); } } }); tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tok_tx.blocking_send(msg).is_err() { break; } } }); let stream = async_stream::stream! { while let Some(msg) = tok_rx.recv().await { let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } pub async fn cluster_browser_stop( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let result = tokio::task::spawn_blocking(move || { crate::cluster_browser::stop_session(&id) }).await; match result { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({"stopped": true})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e.to_string()})), } } /// GET /cluster-home[?user=alice] — the homepage HTML that the /// in-container Firefox loads at startup. Lists discovered services as /// click-cards plus an open-URL bar at the top. Intentionally /// unauthenticated: the Firefox inside the container has a fresh /// profile and no cookies, and the page only exposes information /// that's already visible to anything on the WolfNet routing fabric. /// The optional `user` query param scopes the homepage to that user's /// pinned manual URLs in addition to auto-discovered services — the /// session-start endpoint embeds the user in the homepage URL when it /// spawns the container so each user lands on their own grid. pub async fn cluster_browser_homepage( req: HttpRequest, _state: web::Data, query: web::Query>, ) -> HttpResponse { let _ = req; // intentional — unauthenticated by design let user = query.get("user").map(|s| s.as_str()).unwrap_or(""); let html = crate::cluster_browser::render_homepage(user); HttpResponse::Ok() .insert_header(("Content-Type", "text/html; charset=utf-8")) .insert_header(("Cache-Control", "no-cache")) .body(html) } /// Minimal percent-encoder for the `user` query param embedded in the /// in-container browser's homepage URL. Avoids pulling in a full /// urlencoding crate just for one call site. Encodes everything that /// isn't alphanumeric or `-_.` (RFC 3986 unreserved-ish). fn urlencoding_simple(s: &str) -> String { let mut out = String::with_capacity(s.len()); for byte in s.as_bytes() { let c = *byte; if c.is_ascii_alphanumeric() || c == b'-' || c == b'_' || c == b'.' || c == b'~' { out.push(c as char); } else { out.push_str(&format!("%{:02X}", c)); } } out } /// GET /api/wolfnet/used-ips — returns WolfNet IPs in use on this node /// Requires cluster auth — used for inter-node route discovery pub async fn wolfnet_used_ips_endpoint(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let ips = containers::wolfnet_used_ips(); HttpResponse::Ok().json(ips) } /// GET /api/wolfnet/active-ips — WolfNet IPs of workloads ACTIVE (running) /// on this node. Peers use this for routing (so a stopped container stops /// attracting traffic) and for start-time conflict detection. Distinct from /// /used-ips, which also reports stopped workloads' reserved IPs. pub async fn wolfnet_active_ips_endpoint(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } // Enumeration spawns ip/docker/lxc-ls subprocesses — keep it off the // async worker thread. let ips = web::block(containers::wolfnet_active_ips).await.unwrap_or_default(); HttpResponse::Ok().json(ips) } /// POST /api/wolfnet/routes/announce — accept a route push from a peer. /// /// Body shape: `{ "host_ip": "10.10.10.171", "routes": { "10.10.10.100": /// "10.10.10.171", ... } }`. Every value MUST equal `host_ip` (a peer /// can only announce routes that point at itself — it can't claim to /// own a container that lives on someone else's node). /// /// This is the PUSH side of route propagation, redundant with the /// pull-based poll loop in `agent::poll_remote_nodes`. The pull path /// can silently fail (TLS mismatch, cluster-state staleness, peer's /// /api/agent/status not returning a parseable StatusReport) and leave /// receivers without container routes for hours. The push side adds /// an independent path: even if mouse can't successfully poll dreamer, /// dreamer announcing its routes TO mouse still keeps the routing /// table converged. dreamer was reporting `10.10.10.100→10.10.10.171` /// locally but mouse's `routes.json` had no dreamer entries — exactly /// the failure mode this endpoint defends against. #[derive(Deserialize)] pub struct WolfnetRouteAnnounce { pub host_ip: String, pub routes: std::collections::HashMap, } pub async fn wolfnet_routes_announce( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // Cluster-secret only — this is an inter-node call and must never // be reachable via session/UI auth. WolfNet is intentionally // cluster-scoped: container routes don't propagate across cluster // boundaries even when the wolfnet mesh is shared, so a peer in a // different cluster cannot inject routes here. if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let announce = body.into_inner(); // Anti-spoof: the host_ip and every route value must be IPv4, and // every route value MUST equal host_ip. A peer that tried to // announce `10.10.10.55: 10.10.10.171` would be claiming to own a // container that lives on dreamer — refuse it. if announce.host_ip.parse::().is_err() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "host_ip is not a valid IPv4 address" })); } let mut accepted = std::collections::HashMap::new(); for (container_ip, claimed_host) in announce.routes.iter() { if container_ip.parse::().is_err() { continue; } if claimed_host != &announce.host_ip { tracing::warn!( "wolfnet_routes_announce: refusing route {} → {} (host_ip is {}); peer cannot announce routes pointing elsewhere", container_ip, claimed_host, announce.host_ip ); continue; } if container_ip == &announce.host_ip { // Host's own IP — not a container route. Skip silently. continue; } accepted.insert(container_ip.clone(), claimed_host.clone()); } // First sweep stale entries pointing at this host from this peer // (so a container that moved off the peer doesn't linger). Then // merge the fresh set. Atomic w.r.t. the WOLFNET_ROUTES lock so the // single routes.json write below reflects a consistent state (wolfnetd // picks it up on its 15s tick — flush_routes_to_disk no longer SIGHUPs). let host_ip = announce.host_ip.clone(); let cache_changed = tokio::task::spawn_blocking(move || { use std::collections::HashMap; let mut cache = containers::WOLFNET_ROUTES.lock().unwrap(); let before = cache.clone(); // Drop entries pointing at this host that aren't in the fresh // announce — they've been deleted on the source. cache.retain(|k, v| { if v == &host_ip { accepted.contains_key(k) } else { true } }); for (k, v) in &accepted { cache.insert(k.clone(), v.clone()); } let changed = *cache != before; if changed { // Drop the lock before flush_routes_to_disk reacquires it. let snapshot: HashMap = cache.clone(); drop(cache); containers::flush_routes_to_disk(&snapshot); } changed }).await.unwrap_or(false); HttpResponse::Ok().json(serde_json::json!({ "accepted": true, "host_ip": announce.host_ip, "changed": cache_changed })) } /// Push the local WOLFNET_ROUTES (entries that point at THIS host) to /// every online wolfstack peer in the cluster. Fire-and-forget; each /// peer can fail independently without holding up the others. /// /// Runs on a 30s tick from `main.rs`. Symmetric to `poll_remote_nodes` /// — they pull, this pushes. The combination is robust against either /// path failing on its own. pub async fn announce_wolfnet_routes_to_peers( cluster: std::sync::Arc, cluster_secret: String, ) { // Never announce an empty route set we haven't earned. Peers treat an // announce as authoritative and drop every route pointing back at us, so // an emptied cache propagates cluster-wide as lost container routing. // The cache empties on any reboot (/run is tmpfs) and used to empty on // every upgrade, when stopping WolfNet took its runtime directory with it // (sabur7, G740, 2026-07-27). Re-seeding here means a WolfNet restart // underneath a running WolfStack self-heals, which the startup-only seed // could not do. No-op when the cache is populated. let _ = tokio::task::spawn_blocking(containers::seed_local_routes_if_empty).await; // Build the announce payload first — shared by both discovery paths. let local_ips = containers::wolfnet_active_ips_cached(); let host_ip = match local_ips.first() { Some(ip) if !ip.is_empty() => ip.clone(), _ => { // No wolfnet0 IP yet — nothing to announce. return; } }; let local_routes: std::collections::HashMap = { let cache = containers::WOLFNET_ROUTES.lock().unwrap(); cache .iter() .filter(|(_, v)| *v == &host_ip) .map(|(k, v)| (k.clone(), v.clone())) .collect() }; let payload = serde_json::json!({ "host_ip": host_ip, "routes": local_routes, }); // ── Path 1: Cluster node list (existing mechanism) ── // Push to every online wolfstack peer in OUR cluster. let self_cluster = cluster.get_self_cluster_name(); let cluster_peers: Vec<(String, u16)> = { let nodes = cluster.nodes_read(); nodes .values() .filter(|n| !n.is_self) .filter(|n| n.node_type == "wolfstack") .filter(|n| n.online) .filter(|n| n.cluster_name.as_deref().unwrap_or("WolfStack") == self_cluster) .map(|n| (n.address.clone(), n.port)) .collect() }; let client = API_HTTP_CLIENT.clone(); let mut pushed_hosts: std::collections::HashSet = std::collections::HashSet::new(); for (address, port) in &cluster_peers { pushed_hosts.insert(address.clone()); let urls = build_node_urls(address, *port, "/api/wolfnet/routes/announce"); for url in &urls { let r = client .post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .json(&payload) .send() .await; match r { Ok(resp) => { let success = resp.status().is_success(); let _ = resp.bytes().await; if success { break; } } Err(_) => { /* try next URL in the fallback chain */ } } } } // ── Path 2: WolfNet config.toml peers (ground-truth) ── // The config.toml defines exactly which nodes share this WolfNet // mesh. Push to any peers not already covered by the cluster list. // This is the primary mechanism — it works even when the cluster // node list has stale cluster_names or the peer is temporarily // marked offline. if let Ok(config_str) = std::fs::read_to_string("/etc/wolfnet/config.toml") && let Ok(config) = config_str.parse::() && let Some(peers) = config.get("peers").and_then(|p| p.as_array()) { for peer in peers { let endpoint = match peer.get("endpoint").and_then(|v| v.as_str()) { Some(e) => e, None => continue, }; // endpoint is "hostname:port" — extract hostname // (port-aware: a bare/bracketed IPv6 endpoint must not // be truncated at its first group) let hostname = crate::netaddr::strip_port(endpoint); if hostname.is_empty() { continue; } // Skip if we already pushed to this host via Path 1 if pushed_hosts.contains(hostname) { continue; } // Also check against wolfnet IP — Path 1 might have // used a numeric address while config has a hostname let allowed_ip = peer.get("allowed_ip").and_then(|v| v.as_str()).unwrap_or(""); if pushed_hosts.contains(allowed_ip) { continue; } pushed_hosts.insert(hostname.to_string()); // Try HTTPS on default port, then HTTP, then via wolfnet IP let hostname_url = crate::netaddr::bracket_host(hostname); let urls = vec![ format!("https://{}:8553/api/wolfnet/routes/announce", hostname_url), format!("http://{}:8554/api/wolfnet/routes/announce", hostname_url), format!("http://{}:8554/api/wolfnet/routes/announce", allowed_ip), ]; for url in &urls { let r = client .post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .json(&payload) .send() .await; if let Ok(resp) = r { let success = resp.status().is_success(); let _ = resp.bytes().await; if success { break; } } } } } } /// GET /api/wolfnet/routes — returns the full WOLFNET_ROUTES cache + local used IPs for debugging pub async fn wolfnet_routes_debug(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Get the WOLFNET_ROUTES cache (container_ip -> gateway_host_ip) let routes = containers::WOLFNET_ROUTES.lock().unwrap().clone(); // Get local used IPs with labels let local_ips = containers::wolfnet_used_ips(); let host_ip = local_ips.first().cloned().unwrap_or_default(); // Build a combined view: each IP with its type and route info let mut entries: Vec = Vec::new(); // Local used IPs for (i, ip) in local_ips.iter().enumerate() { entries.push(serde_json::json!({ "ip": ip, "type": if i == 0 { "host" } else { "local" }, "gateway": if i == 0 { "self" } else { &host_ip }, "source": "local" })); } // Remote routes from cache for (ip, gateway) in &routes { // Skip if already in local list if local_ips.contains(ip) { continue; } entries.push(serde_json::json!({ "ip": ip, "type": "remote", "gateway": gateway, "source": "cache" })); } // Also read routes.json for comparison let routes_json = std::fs::read_to_string("/var/run/wolfnet/routes.json") .ok() .and_then(|c| serde_json::from_str::>(&c).ok()) .unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "entries": entries, "routes_cache_count": routes.len(), "routes_json_count": routes_json.len(), "host_ip": host_ip, "local_ips": local_ips, })) } /// GET /api/containers/docker/stats — Docker container stats pub async fn docker_stats(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match web::block(containers::docker_stats_cached).await { Ok(stats) => HttpResponse::Ok().json(stats), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "docker stats unavailable"})), } } /// GET /api/containers/docker/images — list Docker images pub async fn docker_images(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match web::block(containers::docker_images_cached).await { Ok(images) => HttpResponse::Ok().json(images), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "docker images unavailable"})), } } /// DELETE /api/containers/docker/images/{id} — remove a Docker image pub async fn docker_remove_image(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match containers::docker_remove_image(&id) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/containers/docker/{id}/logs — get Docker container logs pub async fn docker_logs(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let logs = containers::docker_logs(&id, 100); HttpResponse::Ok().json(serde_json::json!({ "logs": logs })) } #[derive(Deserialize)] pub struct ContainerActionRequest { pub action: String, // start, stop, restart, remove, pause, unpause /// Skip the managed-container guard on remove/destroy. Set by the UI /// after the operator explicitly confirms force-removal, and by /// WolfRun itself when tearing down its own instances. #[serde(default)] pub force: bool, } /// POST /api/containers/docker/{id}/action — control Docker container /// Returns the label of another cluster node currently running a workload /// with this WolfNet IP, or None if the IP is free to claim here. Used to /// refuse a start that would put a second copy of a live WolfNet address on /// the overlay. A *stopped* holder's reserved IP does NOT count — the check /// is live (queries peers' /api/wolfnet/active-ips), so it won't /// false-positive on a migrate hand-off where the source was just stopped. /// Fails open: if peers can't be reached, the start is allowed. pub(crate) async fn wolfnet_ip_active_elsewhere(state: &web::Data, ip: &str) -> Option { let ip = ip.trim().to_string(); if ip.is_empty() { return None; } // Already active on another running workload on THIS node? { let ip_local = ip.clone(); let hit = web::block(move || containers::wolfnet_active_ips().into_iter().any(|a| a == ip_local)) .await.unwrap_or(false); if hit { return Some("this node".to_string()); } } // Snapshot peer targets, dropping the lock before any await. Scope to // THIS node's cluster only: a WolfNet mesh is cluster-wide, not // fleet-wide — control-plane replication makes every node see the whole // fleet, and separate clusters' meshes legitimately reuse the same // 10.x address space. Checking fleet-wide refused to start an LXC // because an unrelated cluster's workload held the same IP on a // DIFFERENT mesh (operator, 2026-06-10). cluster_eq is case-insensitive // and treats None==None, so an unnamed/standalone fleet keeps the old // behaviour rather than becoming more permissive than its mesh. let targets: Vec<(String, String, u16)> = { let nodes = state.cluster.nodes_read(); let self_cluster: Option = nodes .get(&state.cluster.self_id) .and_then(|n| n.cluster_name.clone()); nodes.values() .filter(|n| !n.is_self && n.online) .filter(|n| crate::agent::cluster_eq( self_cluster.as_deref(), n.cluster_name.as_deref(), )) .map(|n| ( if n.hostname.is_empty() { n.address.clone() } else { n.hostname.clone() }, n.address.clone(), n.port, )) .collect() }; let client = &*API_HTTP_CLIENT; let secret = state.cluster_secret.clone(); for (label, address, port) in targets { // WolfStack serves the API on 8553/8552 even on Proxmox nodes that // are registered with the PVE port. Dedupe so a standard 8553 node // isn't probed twice (each extra port costs a 3s timeout when the // peer is unreachable). let mut ports = vec![8553u16, 8552]; if port != 8553 && port != 8552 { ports.insert(0, port); } 'ports: for p in ports { for url in build_node_urls(&address, p, "/api/wolfnet/active-ips") { let Ok(resp) = client.get(&url) .timeout(std::time::Duration::from_secs(3)) .peer_auth(&secret) .send().await else { continue }; // Drain before leaving — a bare `continue` strands the socket // in CLOSE-WAIT (see drain_response). This runs on every // container start, against every peer, so a peer answering // non-2xx leaks steadily under any start-heavy workload. if !resp.status().is_success() { drain_response(resp).await; continue; } let Ok(ips) = resp.json::>().await else { continue }; if ips.iter().any(|a| a == &ip) { return Some(label); } break 'ports; // definitive answer; this node doesn't hold it } } } None } /// Refusals every path that changes a container's run state must apply — /// the REST action handlers and the MCP tools both call this, so a new /// surface can never start a container the UI would refuse to. `Err` is the /// operator-facing reason (the REST handlers answer it as 409). /// /// * start (Docker + LXC): never bring up a second copy of a WolfNet IP that /// is already live elsewhere in the cluster. /// * start / restart (LXC): a WolfHA standby carries its primary's MAC and /// IP — hand-starting it while the primary runs puts two identical /// containers on one L2. Promotion (the WolfHA page) removes the marker /// before starting. pub(crate) async fn container_lifecycle_guard( state: &web::Data, runtime: &str, name: &str, action: &str, ) -> Result<(), String> { if action == "start" { let (rt, n) = (runtime.to_string(), name.to_string()); // docker_effective_wolfnet_ip can run `docker inspect` (10s cap). let ip = web::block(move || match rt.as_str() { "docker" => containers::docker_effective_wolfnet_ip(&n), "lxc" => containers::lxc_get_wolfnet_ip(&n), _ => None, }).await.unwrap_or(None); if let Some(ip) = ip && let Some(holder) = wolfnet_ip_active_elsewhere(state, &ip).await { return Err(format!("WolfNet IP already in use: {} (active on {})", ip.trim(), holder)); } } if runtime == "lxc" && matches!(action, "start" | "restart") && crate::wolfha::is_replica(name) { return Err(format!( "'{}' is a WolfHA standby — starting it here would collide with the active copy. Use Promote on the WolfHA page instead.", name )); } Ok(()) } pub async fn docker_action( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if let Err(e) = container_lifecycle_guard(&state, "docker", &id, &body.action).await { return HttpResponse::Conflict().json(serde_json::json!({ "error": e })); } // Removing a WolfRun-managed container is futile — the reconciler // recreates it within seconds — and users read the reappearance as // "delete is broken" (klas, 2026-08-12). Refuse unless forced; the // UI turns this 409 into an explanation plus a force-remove confirm. if body.action == "remove" && !body.force { let managers = state.wolfrun.services_managing(&id); if !managers.is_empty() { let names: Vec = managers.into_iter().map(|(_, name)| name).collect(); return HttpResponse::Conflict().json(serde_json::json!({ "error": format!( "'{}' is managed by WolfRun service '{}' — WolfRun will recreate it within seconds. Delete the service on the WolfRun page to remove it for good.", id, names.join("', '") ), "wolfrun_managed": true, "services": names, })); } } // Every arm shells out to docker, and start/restart also sleep 1 s // and re-plumb WolfNet — blocking work, so it leaves the runtime. let action = body.action.clone(); let target = id.clone(); let result = web::block(move || match action.as_str() { "start" => containers::docker_start(&target), "stop" => containers::docker_stop(&target), "restart" => containers::docker_restart(&target), "remove" => containers::docker_remove_permanent(&target), "pause" => containers::docker_pause(&target), "unpause" => containers::docker_unpause(&target), _ => Err(format!("Unknown action: {}", action)), }) .await .unwrap_or_else(|e| Err(format!("container action task failed: {}", e))); match result { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct CloneRequest { pub new_name: String, pub snapshot: Option, // LXC only — use copy-on-write clone pub storage: Option, // target storage (Proxmox ID or path) pub target_node: Option, // clone to a different node in the cluster pub wolfnet_ip: Option, // pre-allocated wolfnet IP (avoids cross-node conflicts) #[serde(default)] pub vmid: Option, // Proxmox local clone — operator-chosen new VMID } #[derive(Deserialize)] pub struct MigrateRequest { pub target_node: String, pub storage: Option, pub new_name: Option, #[serde(default)] pub target_address: Option, #[serde(default)] pub target_port: Option, /// Target's operator-configured migration address (dedicated-NIC IP), /// forwarded by the UI so the source uses the pinned NIC regardless of its /// own gossip view. Empty/absent ⇒ use `Node::migration_host`. #[serde(default)] pub target_migration_address: Option, /// Destination bridge for the container's primary NIC. None = keep /// the source network where the destination can honour it (the /// default translation). The destination validates it exists. #[serde(default)] pub target_bridge: Option, } #[derive(Deserialize)] #[allow(dead_code)] pub struct MigrateExternalRequest { pub target_url: String, pub target_token: String, pub new_name: Option, pub storage: Option, pub delete_source: Option, // accepted but ignored — source is never deleted /// Destination bridge for the container's primary NIC (see /// MigrateRequest::target_bridge). #[serde(default)] pub target_bridge: Option, /// Opt-in: keep the source's IP and MAC on the destination instead of /// assigning a fresh identity. Off by default because two independent /// clusters can share an L2, where duplicating the address collides — /// but for an isolated prod→test move it's exactly what you want /// (jdelrue 2026-08-09). #[serde(default)] pub preserve_address: Option, /// Opt-in: start the container on the destination after transfer. /// Off by default (a cross-cluster copy leaves the source running, so /// booting the copy too would run two of the same container). #[serde(default)] pub start_after: Option, } #[derive(Deserialize)] #[allow(dead_code)] pub struct ImportRequest { pub new_name: String, pub storage: Option, } /// POST /api/containers/docker/{id}/clone — clone a Docker container pub async fn docker_clone( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match containers::docker_clone(&id, &body.new_name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/docker/{id}/migrate — migrate a Docker container to another node #[derive(Deserialize)] pub struct DockerMigrateRequest { pub target_url: String, pub remove_source: Option, /// What to do with the source's volumes — chosen by the operator in the /// migrate dialog. Absent means `declare`: recreate the mounts but never /// silently copy gigabytes of data the operator didn't ask for, and never /// silently drop mounts they expected to keep. #[serde(default)] pub volume_mode: Option, } pub async fn docker_migrate( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let remove = body.remove_source.unwrap_or(false); let volume_mode = body.volume_mode.unwrap_or(containers::VolumeMode::Declare); // web::block, NOT a direct call: docker_migrate is fully blocking (docker // commit, docker save, curl transfers of the image and every copied // volume) and can run for minutes. Called inline it pins an actix worker // for the whole migration — with only `default_workers` of them, and // keep_alive at 2s, the browser's connection is torn down mid-migration // and reports "NetworkError when attempting to fetch resource" // (RutgerDiehard, 2026-08-07). It also blocked every other request that // landed on the same worker. let target_url = body.target_url.clone(); let secret = state.cluster_secret.clone(); let result = web::block(move || { containers::docker_migrate(&id, &target_url, remove, &secret, volume_mode) }).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("migration task failed: {}", e) })), } } /// GET /api/containers/lxc — list all LXC containers pub async fn lxc_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Offload the blocking lxc-ls/lxc-info subprocesses (on a cache miss) to the // blocking pool — see docker_list for why running it inline blanked the list. // UI-facing list — the one caller permitted to probe inside containers. match web::block(|| containers::with_service_probing(containers::lxc_list_all_cached)).await { Ok(containers) => HttpResponse::Ok().json(containers), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "lxc list unavailable"})), } } /// GET /api/containers/lxc/stats — LXC container stats pub async fn lxc_stats(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match web::block(containers::lxc_stats_cached).await { Ok(stats) => HttpResponse::Ok().json(stats), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error": "lxc stats unavailable"})), } } /// GET /api/containers/lxc/{name}/logs — get LXC container logs pub async fn lxc_logs(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let logs = containers::lxc_logs(&name, 100); HttpResponse::Ok().json(serde_json::json!({ "logs": logs })) } /// POST /api/containers/lxc/{name}/reclaim-cache — drop the container's clean /// page cache (cgroup v2 memory.reclaim, bounded to reclaimable file cache so /// it's cache-only — never touches the working set, so the app keeps running). pub async fn lxc_reclaim_cache(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // Subprocess + synchronous kernel reclaim — off the async worker. match web::block(move || containers::lxc_reclaim_cache(&name)).await { Ok(Ok(freed)) => HttpResponse::Ok().json(serde_json::json!({ "freed_bytes": freed })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("reclaim task failed: {}", e) })), } } /// GET /api/containers/lxc/{name}/config — get LXC container config pub async fn lxc_config(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_config(&name) { Some(content) => HttpResponse::Ok().json(serde_json::json!({ "config": content })), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Config not found" })), } } /// GET /api/containers/lxc/{name}/exists — does an LXC container, or a /// leftover directory from an earlier failed restore, already occupy /// this name on this node? The restore dialog calls this so it can warn /// the operator BEFORE a restore that would collide — e.g. an accidental /// second restore of a container that already restored fine. pub async fn lxc_exists(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // The name is interpolated into a filesystem path — reject anything // unsafe rather than stat a traversal path. if !crate::auth::is_safe_name(&name) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "invalid container name" })); } let exists = std::path::Path::new(&format!("/var/lib/lxc/{}", name)).exists() || std::path::Path::new(&format!("/etc/pve/lxc/{}.conf", name)).exists(); HttpResponse::Ok().json(serde_json::json!({ "exists": exists })) } /// PUT /api/containers/lxc/{name}/config — save LXC container config pub async fn lxc_save_config( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_save_config(&name, &body.content) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/lxc/{name}/action — control LXC container pub async fn lxc_action( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); if let Err(e) = container_lifecycle_guard(&state, "lxc", &name, &body.action).await { return HttpResponse::Conflict().json(serde_json::json!({ "error": e })); } // Destroying a WolfRun-managed container is futile — the reconciler // recreates it within seconds (klas, 2026-08-12). Refuse unless // forced; mirrors the Docker guard in docker_action. if body.action == "destroy" && !body.force { let managers = state.wolfrun.services_managing(&name); if !managers.is_empty() { let names: Vec = managers.into_iter().map(|(_, svc_name)| svc_name).collect(); return HttpResponse::Conflict().json(serde_json::json!({ "error": format!( "'{}' is managed by WolfRun service '{}' — WolfRun will recreate it within seconds. Delete the service on the WolfRun page to remove it for good.", name, names.join("', '") ), "wolfrun_managed": true, "services": names, })); } } // lxc-start / pct start poll until RUNNING and lxc_restart is stop + // start — blocking work that pinned an actix worker for its duration. let action = body.action.clone(); let result = web::block(move || match action.as_str() { "start" => containers::lxc_start(&name), "stop" => containers::lxc_stop(&name), "restart" => containers::lxc_restart(&name), "freeze" => containers::lxc_freeze(&name), "unfreeze" => containers::lxc_unfreeze(&name), "destroy" => containers::lxc_destroy(&name), _ => Err(format!("Unknown action: {}", action)), }) .await .unwrap_or_else(|e| Err(format!("container action task failed: {}", e))); match result { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/lxc/{name}/clone — clone an LXC container pub async fn lxc_clone( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // Remote clone: export → transfer → import on target node if let Some(ref target_node_id) = body.target_node { return lxc_remote_clone(&state, &name, &body.new_name, target_node_id, body.storage.as_deref(), body.wolfnet_ip.as_deref(), (None, None)).await; } // Local clone — a full clone requires the source stopped; restart it after. let was_running = containers::lxc_is_running(&name); let _ = containers::lxc_stop(&name); let storage = body.storage.as_deref(); let result = if body.snapshot.unwrap_or(false) { containers::lxc_clone_snapshot(&name, &body.new_name, body.vmid) } else { containers::lxc_clone_local(&name, &body.new_name, storage, body.vmid) }; // Restore the source to the state we found it in (don't leave a // previously-stopped template running just because we cloned it). if was_running { let _ = containers::lxc_start(&name); } match result { Ok(msg) => { // The clone is created STOPPED and is NEVER auto-started — the // operator reviews/changes its identity (IP, hostname, WolfNet // address) and starts it when ready. // // Standalone clones already got a fresh MAC/IP from // lxc_clone_fixup_ip; give the copy a fresh WolfNet IP too so it // can't collide with the source. Proxmox clones are deliberately // left exactly as-is (same config + WolfNet IP) per operator // request — nothing is reseated here. if !containers::is_proxmox() { let _ = std::fs::remove_dir_all(format!("{}/{}/.wolfnet", containers::lxc_base_dir(&body.new_name), body.new_name)); if let Some(ip) = containers::next_available_wolfnet_ip() { let _ = containers::lxc_attach_wolfnet(&body.new_name, &ip); } } HttpResponse::Ok().json(serde_json::json!({ "message": msg })) }, Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Resolve a target node by id, falling back to an explicit address/port /// when the id isn't in local cluster state (e.g. a request proxied to a /// node whose cluster view differs). Returns None only when neither the id /// resolves nor a usable fallback address is supplied. fn resolve_target_node( state: &web::Data, target_node_id: &str, fallback_address: Option<&str>, fallback_port: Option, ) -> Option { if let Some(n) = state.cluster.get_node(target_node_id) { return Some(n); } let addr = fallback_address?; let port = fallback_port.unwrap_or(8553); tracing::info!("Node '{}' not in cluster state, using fallback address {}:{}", target_node_id, addr, port); Some(crate::agent::Node { pubkey: None, manager: true, id: target_node_id.to_string(), address: addr.to_string(), migration_address: None, port, hostname: addr.to_string(), is_self: false, online: true, node_type: "wolfstack".to_string(), last_seen: 0, metrics: None, components: vec![], docker_count: 0, lxc_count: 0, vm_count: 0, compose_count: 0, public_ip: None, pve_token: None, pve_fingerprint: None, pve_node_name: None, pve_cluster_name: None, cluster_name: None, join_verified: false, has_docker: false, has_lxc: false, has_kvm: false, login_disabled: false, tls: false, update_script: None, self_id: None, workload_subnets: Vec::new(), site: None, display_name: None, roles: Vec::new(), poll_interval_secs: None, }) } /// Remote clone: export on this node, stream to target, import there async fn lxc_remote_clone( state: &web::Data, source: &str, new_name: &str, target_node_id: &str, storage: Option<&str>, wolfnet_ip: Option<&str>, fallback: (Option<&str>, Option), ) -> HttpResponse { let (fallback_address, fallback_port) = fallback; // 1. Find target node — fall back to address/port if node ID not in local cluster state // (can happen when request is proxied to a remote node with different cluster state) let node = match resolve_target_node(state, target_node_id, fallback_address, fallback_port) { Some(n) => n, None => return HttpResponse::NotFound().json(serde_json::json!({"error": "Target node not found"})), }; if node.is_self { // Target resolved to this node — a local clone. A full clone needs the // source stopped (pct clone --full / lxc-copy both require it), so stop // it first and restore it to the state we found it in afterwards. let was_running = containers::lxc_is_running(source); let _ = containers::lxc_stop(source); let res = containers::lxc_clone_local(source, new_name, storage, None); if was_running { let _ = containers::lxc_start(source); } match res { Ok(msg) => return HttpResponse::Ok().json(serde_json::json!({"message": msg})), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } // 2. Stop container temporarily for consistent export, then restart immediately let _ = containers::lxc_stop(source); // 3. Export container let (archive_path, meta) = match containers::lxc_export(source) { Ok(v) => v, Err(e) => { let _ = containers::lxc_start(source); return HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Export failed: {}", e)})); } }; // Restart source immediately after export — source stays running during transfer let _ = containers::lxc_start(source); // 4. Read archive let archive_bytes = match std::fs::read(&archive_path) { Ok(b) => b, Err(e) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); return HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Failed to read archive: {}", e)})); } }; // 5. Transfer to target // For Proxmox-type nodes, WolfStack is also installed on the server but the // node is registered with the PVE API port (8006), not the WolfStack port (8553). // Build import URLs using the correct WolfStack port. let import_urls = if node.node_type == "proxmox" { // Proxmox nodes have WolfStack running on port 8553 — try that let mut urls = build_node_urls(&node.address, 8553, "/api/containers/lxc/import"); // Also try 8552 as a fallback WolfStack port urls.extend(build_node_urls(&node.address, 8552, "/api/containers/lxc/import")); urls } else { build_node_urls(&node.address, node.port, "/api/containers/lxc/import") }; let storage_val = storage.unwrap_or("").to_string(); let client = &*API_HTTP_CLIENT; let file_name = archive_path.file_name().unwrap_or_default().to_string_lossy().to_string(); let meta_json = serde_json::to_string(&meta).unwrap_or_default(); let mut last_err: Option = None; for import_url in &import_urls { let mut form = reqwest::multipart::Form::new() .text("new_name", new_name.to_string()) .text("storage", storage_val.clone()) .text("meta", meta_json.clone()) .part("archive", reqwest::multipart::Part::bytes(archive_bytes.clone()) .file_name(file_name.clone())); // Pass pre-allocated wolfnet IP to avoid cross-node conflicts if let Some(ip) = wolfnet_ip { form = form.text("wolfnet_ip", ip.to_string()); } match client.post(import_url) .timeout(std::time::Duration::from_secs(600)) .peer_auth(state.cluster_secret.clone()) .multipart(form) .send() .await { Ok(r) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); if r.status().is_success() { return match r.json::().await { Ok(data) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Container '{}' cloned to '{}' on node '{}'", source, new_name, target_node_id), "detail": data })), Err(_) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Container '{}' cloned to '{}' on node '{}'", source, new_name, target_node_id) })), }; } else { let err_text = r.text().await.unwrap_or_default(); return HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Import on target failed: {}", err_text)})); } } Err(e) => { last_err = Some(e.to_string()); continue; // Try next URL } } } // All URLs failed — source is already running containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("Transfer to {} failed on all ports/protocols: {}", node.address, last_err.unwrap_or_default()) })) } /// POST /api/containers/lxc/{name}/export — export container as downloadable archive pub async fn lxc_export_endpoint( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // Stop, export, restart let _ = containers::lxc_stop(&name); let (archive_path, meta) = match containers::lxc_export(&name) { Ok(v) => v, Err(e) => { let _ = containers::lxc_start(&name); return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } }; let _ = containers::lxc_start(&name); // Read the file and return as binary download match std::fs::read(&archive_path) { Ok(bytes) => { let filename = archive_path.file_name().unwrap_or_default().to_string_lossy().to_string(); containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); HttpResponse::Ok() .insert_header(("Content-Disposition", format!("attachment; filename=\"{}\"", filename))) .insert_header(("X-Container-Meta", serde_json::to_string(&meta).unwrap_or_default())) .content_type("application/octet-stream") .body(bytes) } Err(e) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Read archive: {}", e)})) } } } /// POST /api/containers/lxc/import — import container from uploaded archive (multipart) pub async fn lxc_import_endpoint( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } lxc_import_endpoint_inner(&mut payload).await } /// POST /api/containers/lxc/{name}/migrate — move a container to another /// node in the same cluster. Unlike a clone, this is a true move: the /// source is stopped, transferred, imported with a bootable config, then /// the destination is started and verified RUNNING. The source is left /// stopped (kept on the old node as a rollback). On any failure the /// source is restarted. Runs in the background — the response carries a /// `task_id`; poll GET /api/migration/{id}/status for live progress. pub async fn lxc_migrate( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // Validate here, before we stop/export anything — a bad name must not // cost the operator downtime only to be rejected by the target later. // The URL name doubles as the destination-name fallback and is // interpolated into the preflight check URL, so it gets the same gate. if !crate::auth::is_safe_name(&name) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let requested_name = body.new_name.as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(String::from); if let Some(ref n) = requested_name && !crate::auth::is_safe_name(n) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // Resolve the destination up front so a bad target fails fast (before // we stop anything) rather than inside the background task. let mut node = match resolve_target_node(&state, &body.target_node, body.target_address.as_deref(), body.target_port) { Some(n) => n, None => return HttpResponse::NotFound().json(serde_json::json!({"error": "Target node not found"})), }; if node.is_self { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Target is the source node — migrate moves a container between nodes; use Clone to copy it on the same host" })); } // The UI forwards the target's operator-configured migration address (from // the master's full cluster view) so the upload uses the pinned NIC even if // THIS node's gossip view of the target predates the setting. if let Some(ma) = body.target_migration_address.as_deref().map(str::trim).filter(|s| !s.is_empty()) { node.migration_address = Some(ma.to_string()); } // Build the import endpoints up front (Proxmox nodes register their PVE // port, but WolfStack listens on 8553/8552 there). The bulk transfer rides // the migration NIC if the operator pinned one (migration_host). let mig_host = node.migration_host(); let mut import_urls = if node.node_type == "proxmox" { let mut urls = build_node_urls(mig_host, 8553, "/api/containers/lxc/import"); urls.extend(build_node_urls(mig_host, 8552, "/api/containers/lxc/import")); urls } else { build_node_urls(mig_host, node.port, "/api/containers/lxc/import") }; // Fallback to the node's normal address if a distinct migration NIC was // pinned but is unreachable — never fail a migration on the fast path. if mig_host != node.address { if node.node_type == "proxmox" { import_urls.extend(build_node_urls(&node.address, 8553, "/api/containers/lxc/import")); import_urls.extend(build_node_urls(&node.address, 8552, "/api/containers/lxc/import")); } else { import_urls.extend(build_node_urls(&node.address, node.port, "/api/containers/lxc/import")); } } // Same endpoints, name-collision preflight route. let check_urls: Vec = import_urls.iter() .map(|u| u.replace("/api/containers/lxc/import", "/api/containers/lxc/import-name-check")) .collect(); let target_label = if node.hostname.is_empty() { node.address.clone() } else { node.hostname.clone() }; let target_addr = node.address.clone(); let target_is_proxmox = node.node_type == "proxmox"; let tasks = state.migration_tasks.clone(); let task_id = migration_create(&tasks); let tid = task_id.clone(); let cluster_secret = state.cluster_secret.clone(); let storage_val = body.storage.as_deref().unwrap_or("").to_string(); let target_bridge = body.target_bridge.as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(String::from); tokio::spawn(async move { // 0. An explicitly-chosen destination name can be collision-checked // before ANYTHING is stopped — zero downtime on a name clash. // (RutgerDiehard 2026-08-08: the old flow only found out after // the stop + export + upload.) if let Some(ref rn) = requested_name && remote_lxc_name_taken(&check_urls, rn, Some(&cluster_secret), None).await { migration_fail(&tasks, &tid, &format!( "'{}' already exists on {} — nothing was stopped or transferred. Pick a different Destination name in the migrate dialog and run it again.", rn, target_label)); return; } // 1. Stop the source for a consistent export. Record whether it was // running so a rollback only restarts a previously-running one. migration_update(&tasks, &tid, "stop_source", &format!("Stopping '{}' on the source node…", name)); let was_running = containers::lxc_is_running(&name); let _ = containers::lxc_stop(&name); // Refuse to export a still-running rootfs — the archive would be // inconsistent. The source is untouched here, so just abort. if containers::lxc_is_running(&name) { migration_fail(&tasks, &tid, &format!( "Could not stop '{}' on the source node — aborted before export so no inconsistent copy is shipped. The source is still running, untouched.", name)); return; } // 2. Export (stays stopped — this is a move, not a live clone). migration_update(&tasks, &tid, "export", "Exporting container…"); let (archive_path, meta) = match containers::lxc_export(&name) { Ok(v) => v, Err(e) => { if was_running { let _ = containers::lxc_start(&name); } migration_fail(&tasks, &tid, &format!("Export failed: {}", e)); return; } }; let archive_bytes = match std::fs::read(&archive_path) { Ok(b) => b, Err(e) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); if was_running { let _ = containers::lxc_start(&name); } migration_fail(&tasks, &tid, &format!("Failed to read archive: {}", e)); return; } }; // Destination name: the operator's explicit choice, else the source's // real hostname from the export metadata. On a Proxmox source `name` // is the bare VMID — defaulting to it named the arrival "131" (and on // a PVE destination set hostname to the old VMID, the exact // fingerprint the ghost-husk heuristic hides). See lxc_migrate_external. let new_name = requested_name.clone().unwrap_or_else(|| { if meta.name != name && crate::auth::is_safe_name(&meta.name) { meta.name.clone() } else { name.clone() } }); // The defaulted name is only known post-export — collision-check it // before paying for the upload. (An explicit name was already // checked before the source was stopped.) if requested_name.is_none() && remote_lxc_name_taken(&check_urls, &new_name, Some(&cluster_secret), None).await { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); if was_running { let _ = containers::lxc_start(&name); } migration_fail(&tasks, &tid, &format!( "'{}' already exists on {} — nothing was transferred, source restarted. Set a different Destination name in the migrate dialog and run it again.", new_name, target_label)); return; } let size_mb = archive_bytes.len() / (1024 * 1024); migration_update(&tasks, &tid, "upload", &format!("Transferring {} MB to {}…", size_mb, target_label)); // 3. Upload → target imports a bootable config, starts + verifies it. let client = &*API_HTTP_CLIENT; let file_name = archive_path.file_name().unwrap_or_default().to_string_lossy().to_string(); let meta_json = serde_json::to_string(&meta).unwrap_or_default(); // Carry the source's exact WolfNet IP so the destination keeps it — // a move reproduces the container as-is (the source is stopped, so // there is no IP conflict). let src_wolfnet_ip = containers::lxc_get_wolfnet_ip(&name); let mut last_err: Option = None; // A connect failure means nothing was sent (safe to restart the // source). A timeout or any other error is ambiguous — the target // may already have imported AND started the container, so restarting // the source would leave two copies running (split-brain). let mut saw_ambiguous = false; for import_url in &import_urls { let mut form = reqwest::multipart::Form::new() .text("new_name", new_name.clone()) .text("storage", storage_val.clone()) .text("meta", meta_json.clone()) .text("start", "1") .text("preserve_identity", "1") .part("archive", reqwest::multipart::Part::bytes(archive_bytes.clone()) .file_name(file_name.clone())); if let Some(ip) = src_wolfnet_ip.clone() { form = form.text("wolfnet_ip", ip); } if let Some(b) = target_bridge.clone() { form = form.text("target_bridge", b); } match client.post(import_url) .timeout(std::time::Duration::from_secs(3600)) .peer_auth(cluster_secret.clone()) .multipart(form) .send() .await { Ok(r) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); let status = r.status(); let data = r.json::().await.unwrap_or_else(|_| serde_json::json!({})); if status.is_success() { migration_update(&tasks, &tid, "start", &format!("Starting '{}' on {}…", new_name, target_label)); let started = data.get("started").and_then(|v| v.as_bool()).unwrap_or(false); if started { // Standalone→Proxmox creates a fresh PVE config from // the rootfs (pct create) — custom limits don't carry. let note = if target_is_proxmox && meta.source_type == "standalone" { "\n\nNote: imported onto Proxmox from a standalone node — custom resource limits / LXC settings were not translated; review with `pct config` and adjust via `pct set`." } else { "" }; // The import's own message carries the network- // fallback warning (wrong-bridge → vmbr0/lxcbr0). // It MUST reach this dialog — discarding it here is // how RutgerDiehard's LXC landed on the management // VLAN with no warning shown (2026-08-07). let import_warning = data.get("message").and_then(|v| v.as_str()) .and_then(|m| m.find("WARNING:").map(|i| format!("\n\n{}", &m[i..]))) .unwrap_or_default(); migration_done(&tasks, &tid, &format!( "Migrated '{}' to {} as '{}' — destination is running. Source stopped and kept on the old node as a rollback.{}{}", name, target_label, new_name, import_warning, note)); } else { // Imported but didn't boot — roll back to the source. if was_running { let _ = containers::lxc_start(&name); } let serr = data.get("start_error").and_then(|v| v.as_str()) .unwrap_or("destination did not reach RUNNING"); migration_fail(&tasks, &tid, &format!( "Destination imported but failed to start — source restarted, nothing lost.\n\n{}", serr)); } } else { if was_running { let _ = containers::lxc_start(&name); } let err_text = data.get("error").and_then(|v| v.as_str()).map(|s| s.to_string()) .unwrap_or_else(|| format!("HTTP {}", status)); migration_fail(&tasks, &tid, &format!("Import on target failed — source restarted: {}", err_text)); } return; } Err(e) => { if !e.is_connect() { saw_ambiguous = true; } last_err = Some(e.to_string()); continue; } } } // Transfer failed on every endpoint. containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); if saw_ambiguous { // The destination MAY have received and started the container. // Do NOT restart the source — two running copies risk split-brain // (critical for clustered DBs like Galera). Leave it stopped and // make the operator reconcile. migration_fail(&tasks, &tid, &format!( "Transfer to {} timed out or failed ambiguously — the destination may have started the container. Left the source STOPPED to avoid running two copies; check {} and start whichever copy you want to keep. ({})", target_addr, target_addr, last_err.unwrap_or_default())); } else { // Pure connect failures: nothing was sent, safe to bring it back. if was_running { let _ = containers::lxc_start(&name); } migration_fail(&tasks, &tid, &format!( "Could not connect to {} on any port — nothing was sent, source restarted: {}", target_addr, last_err.unwrap_or_default())); } }); HttpResponse::Ok().json(serde_json::json!({ "task_id": task_id })) } // ─── Cross-cluster Transfer Tokens ─── static TRANSFER_TOKENS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new())); #[derive(Clone, Debug)] struct TransferToken { token: String, expires: std::time::Instant, } /// POST /api/containers/transfer-token — generate a one-time import token pub async fn generate_transfer_token( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let token = format!("wst_{}", uuid::Uuid::new_v4().to_string().replace('-', "")); let expires = std::time::Instant::now() + std::time::Duration::from_secs(1800); // 30 min if let Ok(mut tokens) = TRANSFER_TOKENS.lock() { // Purge expired tokens.retain(|t| t.expires > std::time::Instant::now()); tokens.push(TransferToken { token: token.clone(), expires }); } HttpResponse::Ok().json(serde_json::json!({ "token": token, "expires_in_seconds": 1800, "instructions": "Provide this token to the source cluster to authorize a container transfer." })) } /// Validate and consume a transfer token. /// /// Each candidate is compared with `validate_cluster_secret`, the /// full-walk constant-time comparison, not `==`: a plain string /// equality returns at the first mismatching byte, so response timing /// would reveal how many leading bytes of a guess were correct /// (CWE-208). The transfer token is one of three independently /// sufficient credentials on the import endpoints, so it deserves the /// same treatment as the cluster secret. pub(crate) fn validate_transfer_token(token: &str) -> bool { if let Ok(mut tokens) = TRANSFER_TOKENS.lock() { tokens.retain(|t| t.expires > std::time::Instant::now()); // purge expired if let Some(pos) = tokens.iter().position(|t| crate::auth::validate_cluster_secret(token, &t.token)) { tokens.remove(pos); // consume return true; } } false } /// Validate a transfer token WITHOUT consuming it — for read-only /// preflight checks (name collision) ahead of the import that will /// actually spend the token. pub(crate) fn peek_transfer_token(token: &str) -> bool { if let Ok(mut tokens) = TRANSFER_TOKENS.lock() { tokens.retain(|t| t.expires > std::time::Instant::now()); // purge expired // Constant-time per candidate — see validate_transfer_token. return tokens.iter().any(|t| crate::auth::validate_cluster_secret(token, &t.token)); } false } /// GET /api/containers/lxc/import-name-check?name= — would an import /// under this name collide here? Lets a migrate orchestrator fail fast /// (before stopping/exporting/uploading anything) instead of the /// operator discovering the collision after the transfer. Auth mirrors /// import-external, but the transfer token is only peeked, never spent. pub async fn lxc_import_name_check( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { let has_secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .map(|v| crate::auth::validate_inter_node_secret_from(v, &state.cluster_secret, peer_ip(&req))) .unwrap_or(false); let has_token = req.headers().get("X-Transfer-Token") .and_then(|v| v.to_str().ok()) .map(peek_transfer_token) .unwrap_or(false); if !has_secret && !has_token && let Err(resp) = require_auth(&req, &state) { return resp; } let name = match query.get("name").map(|s| s.trim()).filter(|s| !s.is_empty()) { Some(n) => n.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({"error": "name parameter required"})), }; let taken = web::block(move || containers::lxc_import_name_taken(&name)).await.unwrap_or(false); HttpResponse::Ok().json(serde_json::json!({ "taken": taken })) } // ─── WolfHA: manual high availability for native LXC (Phase 1) ─── /// Peer-or-session auth shared by the WolfHA endpoints that other nodes /// call (manifest / apply-delta / receive-seed / status / demote / drop). fn wolfha_peer_auth(req: &HttpRequest, state: &web::Data) -> Result<(), HttpResponse> { let has_secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .map(|v| crate::auth::validate_inter_node_secret_from(v, &state.cluster_secret, peer_ip(req))) .unwrap_or(false); if has_secret { return Ok(()); } match require_auth(req, state) { Ok(_) => Ok(()), Err(resp) => Err(resp), } } /// This node's own identity as an HaPeer — the address peers should /// call back on. The registry's SELF entry often carries the listen /// address (`0.0.0.0`), which is useless to a peer — fall back to this /// node's own WolfNet IP (the overlay peers reach us on) in that case. fn wolfha_self_peer(state: &web::Data) -> Result { let me = state.cluster.get_all_nodes().into_iter().find(|n| n.is_self) .ok_or_else(|| "this node's own cluster identity is not established yet".to_string())?; let unusable = me.address.is_empty() || me.address == "0.0.0.0" || me.address.starts_with("127."); let address = if unusable { crate::networking::detect_wolfnet_gateway_ip().ok_or_else(|| { "this node's registry address is unroutable (0.0.0.0) and it has no WolfNet IP — peers would have no way to call back".to_string() })? } else { me.address }; Ok(crate::wolfha::HaPeer { node_id: me.id, address, port: me.port }) } /// Seconds since the cluster last saw `node_id` alive, if it counts it /// online and fresh within that node's own online window — the same test /// the automatic failover's "one-sided network problem" gate uses /// (`wolfha::failover_monitor_forever`), so a manual promote and an /// automatic one refuse in exactly the same situations. `None` = offline, /// stale, or unknown. fn wolfha_peer_seen_online(cluster: &crate::agent::ClusterState, node_id: &str) -> Option { let n = cluster.get_node(node_id)?; if n.is_self || !n.online { return None; } let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); let ago = now.saturating_sub(n.last_seen); (ago < cluster.online_window_for(&n)).then_some(ago) } /// GET /api/wolfha/list — this node's HA entries plus live state. pub async fn wolfha_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let blk = web::block(|| { let store = crate::wolfha::HaStore::load(); let enriched: Vec = store.entries.iter().map(|e| { let mut v = serde_json::to_value(e).unwrap_or_default(); if let Some(obj) = v.as_object_mut() { // Ask the right runtime: a protected VM checked with // lxc_is_running would always render as stopped. obj.insert("active".into(), serde_json::Value::Bool(crate::wolfha::subject_is_running(e.kind, &e.container))); } v }).collect(); enriched }).await; match blk { Ok(entries) => { // Ride the in-flight / failed protect attempts along so the // page shows a container from the moment Protect is clicked // — not only after the seed succeeds. let protecting: Vec = wolfha_attempts_lock().iter() .map(|(container, a)| serde_json::json!({ "container": container, "message": a.message, "error": a.error, "updated_at": a.updated_at, })) .collect(); HttpResponse::Ok().json(serde_json::json!({ "entries": entries, "protecting": protecting })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/protect-dismiss — clear a FAILED protect attempt /// from the list (an in-flight one stays; dismissing it would hide a /// task that is still running). pub async fn wolfha_protect_dismiss( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); let mut attempts = wolfha_attempts_lock(); match attempts.get(&container) { Some(a) if a.error.is_some() => { attempts.remove(&container); HttpResponse::Ok().json(serde_json::json!({ "message": "dismissed" })) } Some(_) => HttpResponse::BadRequest().json(serde_json::json!({ "error": "that protect is still running — it can't be dismissed" })), None => HttpResponse::Ok().json(serde_json::json!({ "message": "nothing to dismiss" })), } } /// GET /api/wolfha/status?container= — role/active/staleness of one /// container here. Used by peers (boot guard) and the UI. pub async fn wolfha_status( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let Some(container) = query.get("container").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else { return HttpResponse::BadRequest().json(serde_json::json!({"error": "container parameter required"})); }; if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let blk = web::block(move || { let store = crate::wolfha::HaStore::load(); // The failover monitor reads this to decide whether the primary is // still up. Checking a VM with lxc_is_running would report it // stopped every time and could drive a takeover of a VM that is // running perfectly well. let kind = store.get(&container).map(|e| e.kind).unwrap_or_default(); let active = crate::wolfha::subject_is_running(kind, &container); match store.get(&container) { Some(e) => serde_json::json!({ "role": match e.role { crate::wolfha::HaRole::Primary => "primary", crate::wolfha::HaRole::Replica => "replica" }, "active": active, "stale": e.stale, "last_delta_at": e.last_delta_at, }), None => serde_json::json!({ "role": "none", "active": active }), } }).await; match blk { Ok(v) => HttpResponse::Ok().json(v), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/wolfha/manifest?container= — rootfs manifest of a local /// WolfHA-managed copy, for the primary's diff. Restricted to /// containers with a WolfHA entry so this can't be used to walk an /// arbitrary container's filesystem metadata. pub async fn wolfha_manifest( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let Some(container) = query.get("container").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else { return HttpResponse::BadRequest().json(serde_json::json!({"error": "container parameter required"})); }; if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let blk = web::block(move || -> Result, String> { let store = crate::wolfha::HaStore::load(); if store.get(&container).is_none() { return Err(format!("'{}' is not WolfHA-managed on this node", container)); } let rootfs = format!("{}/{}/rootfs", containers::lxc_base_dir(&container), container); crate::wolfha::build_manifest(&rootfs) }).await; match blk { Ok(Ok(m)) => HttpResponse::Ok().json(m), Ok(Err(e)) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/wolfha/capabilities?container= — which replication drivers /// this node can use for a subject. /// /// The primary probes this before every sync and uses the best driver /// BOTH ends support. A node running a build without this endpoint 404s, /// and the caller treats that as "floor only" — which is exactly the /// pre-existing whole-file behaviour, so a mixed-version cluster keeps /// working rather than half-upgrading into a payload the old side cannot /// read. pub async fn wolfha_capabilities( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let Some(container) = query.get("container").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else { return HttpResponse::BadRequest().json(serde_json::json!({"error": "container parameter required"})); }; if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // A Proxmox-container probe names the datasets and needs no entry: // it is what a primary asks BEFORE seeding, to learn whether this // node can hold the container at all. let pve_probe = query.get("kind").map(|k| k.trim() == "pve_container").unwrap_or(false); let datasets: Vec = query.get("datasets") .map(|d| d.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()) .unwrap_or_default(); let blk = web::block(move || -> Result { if pve_probe { let mut caps = crate::wolfha::replication::detect_pve_capabilities(&datasets, true); // A VMID this node (or its Proxmox cluster) already uses for // something that is not our copy can never be seeded here — // say so at probe time, not after the first stream starts. let store = crate::wolfha::HaStore::load(); if store.get(&container).is_none() { let taken = crate::wolfha::replication::zfs_send::vmid_config_paths(&container); if !taken.is_empty() { caps.notes.push(format!("VMID {} is already in use here ({})", container, taken.join(", "))); caps.drivers.retain(|d| *d != crate::wolfha::replication::DriverKind::ZfsSend); } } return Ok(caps); } let store = crate::wolfha::HaStore::load(); if store.get(&container).is_none() { return Err(format!("'{}' is not WolfHA-managed on this node", container)); } let rootfs = format!("{}/{}/rootfs", containers::lxc_base_dir(&container), container); Ok(crate::wolfha::replication::detect_container_capabilities(&rootfs)) }).await; match blk { Ok(Ok(c)) => HttpResponse::Ok().json(c), Ok(Err(e)) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/wolfha/zfs-snapshots?container=VMID — which WolfHA /// replication snapshots this standby holds, per dataset. The primary's /// incremental base inventory (replication::zfs_send). pub async fn wolfha_zfs_snapshots( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let Some(vmid) = query.get("container").map(|s| s.trim().to_string()) else { return HttpResponse::BadRequest().json(serde_json::json!({"error": "container parameter required"})); }; if !crate::wolfha::replication::zfs_send::is_vmid(&vmid) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container id"})); } match web::block(move || crate::wolfha::pve_replica_snapshots(&vmid)).await { Ok(map) => HttpResponse::Ok().json(map), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/receive-zfs — a primary streams one dataset of a /// Proxmox container into this standby's `zfs receive`. /// /// The multipart body carries its text fields BEFORE the `stream` part; /// everything is validated when that part is reached, so a request that /// cannot succeed is refused before a byte of the stream is read and the /// primary's `zfs send` is cut off by the error instead of pouring /// gigabytes into a doomed request. The stream is piped straight into /// the child's stdin — never staged on disk, never held in memory. pub async fn wolfha_receive_zfs( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { use futures::StreamExt; use tokio::io::AsyncWriteExt; if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let mut fields: std::collections::HashMap = std::collections::HashMap::new(); while let Some(item) = payload.next().await { let mut field = match item { Ok(f) => f, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("multipart error: {}", e) })), }; let name = field.name().unwrap_or("").to_string(); if name != "stream" { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } fields.insert(name, String::from_utf8_lossy(&buf).to_string()); continue; } let f = fields.clone(); let plan = match web::block(move || crate::wolfha::pve_prepare_receive(&f)).await { Ok(Ok(p)) => p, Ok(Err(e)) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), }; let mut child = match tokio::process::Command::new("zfs") .args(&plan.args) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true) .spawn() { Ok(c) => c, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("spawn zfs receive: {}", e) })), }; let Some(mut stdin) = child.stdin.take() else { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "zfs receive: no stdin" })); }; let mut bytes: u64 = 0; let mut upload_err: Option = None; while let Some(chunk) = field.next().await { let data = match chunk { Ok(d) => d, Err(e) => { upload_err = Some(format!("upload read: {}", e)); break; } }; if let Err(e) = stdin.write_all(&data).await { upload_err = Some(format!("zfs receive stopped accepting data: {}", e)); break; } bytes += data.len() as u64; } drop(stdin); let out = match child.wait_with_output().await { Ok(o) => o, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("zfs receive: {}", e) })), }; let zfs_err = String::from_utf8_lossy(&out.stderr).trim().to_string(); if let Some(e) = upload_err { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("{} ({} bytes received{})", e, bytes, if zfs_err.is_empty() { String::new() } else { format!("; zfs: {}", zfs_err) }) })); } if !out.status.success() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("zfs receive of {} failed after {} bytes: {}", plan.dataset, bytes, zfs_err) })); } let f = fields.clone(); return match web::block(move || crate::wolfha::pve_commit_receive(&f, &plan).map(|_| plan.dataset)).await { Ok(Ok(dataset)) => { tracing::info!("wolfha: received ZFS stream of {} ({} bytes)", dataset, bytes); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "bytes": bytes })) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("stream received but the standby could not be recorded: {}", e) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), }; } HttpResponse::BadRequest().json(serde_json::json!({ "error": "the request carried no stream part" })) } /// Undo a failed Proxmox-container protect: no entry, boot flag as it /// was, replication snapshots gone. The container itself was never /// touched beyond its `onboot` flag. async fn wolfha_enable_pve_unwind( container: &str, datasets: &[String], had_onboot: bool, tasks: &std::sync::Arc>>, tid: &str, why: String, ) { let mut st = crate::wolfha::HaStore::load(); st.remove(container); let _ = st.save(); let (c, ds) = (container.to_string(), datasets.to_vec()); let _ = tokio::task::spawn_blocking(move || { if had_onboot { let _ = crate::wolfha::pve_set_onboot(&c, true); } crate::wolfha::pve_destroy_our_snapshots(&c, &ds); }).await; wolfha_protect_fail(container, &why); migration_fail(tasks, tid, &why); } /// Protect a Proxmox container on ZFS: probe every standby, take over the /// boot flag, record the entry, and run the first round (a full stream to /// each standby). Any failure unwinds completely — no entry, boot flag /// restored, replication snapshots destroyed — so a failed protect leaves /// the container exactly as it was. #[allow(clippy::too_many_arguments)] async fn wolfha_enable_pve( container: String, peers: Vec, interval: u64, auto_failover: bool, witness: String, failover_after: u64, self_peer: crate::wolfha::HaPeer, secret: String, cluster: Arc, tasks: std::sync::Arc>>, tid: String, ) { let fail = |msg: String| { wolfha_protect_fail(&container, &msg); migration_fail(&tasks, &tid, &msg); }; migration_update(&tasks, &tid, "seed", "Checking the container's volumes and every standby…"); wolfha_protect_note(&container, "Checking the container's volumes and every standby…"); let c = container.clone(); let datasets = match tokio::task::spawn_blocking(move || crate::wolfha::pve_datasets(&c)).await { Ok(Ok(d)) => d, Ok(Err(e)) => return fail(format!("cannot protect this container: {}", e)), Err(e) => return fail(format!("{}", e)), }; let local = crate::wolfha::replication::detect_pve_capabilities(&datasets, false); if let Some(why) = crate::wolfha::replication::pve_replication_blocked_reason(&local) { return fail(format!("cannot protect this container: {}", why)); } for peer in &peers { if let Err(e) = crate::wolfha::pve_probe_replica(&container, peer, &secret, &datasets).await { return fail(format!("cannot protect this container: {}", e)); } } let c = container.clone(); let had_onboot = match tokio::task::spawn_blocking(move || { let cfg = crate::wolfha::pve_read_config(&c)?; let on = crate::wolfha::replication::zfs_send::config_onboot(&cfg); if on { crate::wolfha::pve_set_onboot(&c, false)?; } Ok::(on) }).await { Ok(Ok(v)) => v, Ok(Err(e)) => return fail(format!("could not take over the container's boot flag: {}", e)), Err(e) => return fail(format!("{}", e)), }; let mut store = crate::wolfha::HaStore::load(); store.remove(&container); store.entries.push(crate::wolfha::HaEntry { container: container.clone(), kind: crate::wolfha::SubjectKind::PveContainer, role: crate::wolfha::HaRole::Primary, interval_minutes: interval, replicas: peers.clone(), primary: None, autostart_managed: had_onboot, last_sync: std::collections::HashMap::new(), last_delta_at: 0, stale: false, pending_vm_delta: None, vm_chain: None, auto_failover, witness, failover_after_secs: failover_after, self_identity: Some(self_peer), zfs_datasets: datasets.clone(), bind_requirements: Vec::new(), }); if let Err(e) = store.save() { let c = container.clone(); if had_onboot { let _ = tokio::task::spawn_blocking(move || crate::wolfha::pve_set_onboot(&c, true)).await; } return fail(format!("could not save the HA entry: {}", e)); } migration_update(&tasks, &tid, "seed", &format!("Streaming {} dataset(s) to {} standby(s) with zfs send (the container keeps running)…", datasets.len(), peers.len())); wolfha_protect_note(&container, &format!("Streaming {} dataset(s) to {} standby(s) with zfs send…", datasets.len(), peers.len())); if let Err(e) = crate::wolfha::sync_container_now(&container, &cluster).await { return wolfha_enable_pve_unwind(&container, &datasets, had_onboot, &tasks, &tid, format!("Seeding failed: {}. No HA entry was created — fix the cause and try again.", e)).await; } let failures: Vec = crate::wolfha::HaStore::load().get(&container) .map(|e| e.last_sync.iter().filter(|(_, s)| !s.ok).map(|(n, s)| format!("{}: {}", n, s.message)).collect()) .unwrap_or_default(); if !failures.is_empty() { return wolfha_enable_pve_unwind(&container, &datasets, had_onboot, &tasks, &tid, format!("Seeding failed on {} — {}. No HA entry was created — fix the node and try again.", if failures.len() == 1 { "a standby" } else { "standbys" }, failures.join("; "))).await; } wolfha_protect_clear(&container); migration_done(&tasks, &tid, &format!( "'{}' is protected — {} standby(s) hold a ZFS copy of {} dataset(s); incremental sends every {} min.", container, peers.len(), datasets.len(), interval)); } #[derive(serde::Deserialize)] pub struct WolfhaSignatureRequest { pub container: String, /// Rootfs-relative paths the primary intends to delta-encode. pub paths: Vec, } /// POST /api/wolfha/signatures — block signatures for the replica's copy /// of specific files, so the primary can send only changed blocks. /// /// Returns `{path: base64(signature)}`. Base64 rather than a binary frame /// because a signature is ~20 bytes per 64 KiB block — 0.03% of the file /// it describes — so the encoding overhead is irrelevant next to the /// clarity of a JSON error path shared with every other endpoint here. /// /// A path the replica does not have is simply absent from the reply; the /// primary then sends that file whole. pub async fn wolfha_signatures( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let b = body.into_inner(); if !crate::auth::is_safe_name(&b.container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // Bound the request: a peer asking for signatures over a huge path // list would pin a worker hashing files for an unbounded time. if b.paths.len() > 10_000 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "too many paths in one signature request (max 10000)" })); } let blk = web::block(move || -> Result { use base64::Engine; let store = crate::wolfha::HaStore::load(); if store.get(&b.container).is_none() { return Err(format!("'{}' is not WolfHA-managed on this node", b.container)); } let rootfs = format!("{}/{}/rootfs", containers::lxc_base_dir(&b.container), b.container); let mut out = serde_json::Map::new(); for rel in &b.paths { // Same guard the delta applier uses: a peer must not be able // to make us read outside the container's rootfs. if !crate::wolfha::is_safe_rel_path(rel) { continue; } let full = format!("{}/{}", rootfs, rel); // Only regular files have block signatures; a symlink or // directory here means the two ends disagree about the kind, // which the manifest diff already handles by resending. match std::fs::symlink_metadata(&full) { Ok(m) if m.is_file() => {} _ => continue, } if let Ok(sig) = crate::wolfha::replication::rolling::signatures( &full, crate::wolfha::replication::rolling::BLOCK_SIZE, ) { let blob = crate::wolfha::replication::rolling::encode_signatures(&sig); out.insert( rel.clone(), serde_json::Value::String( base64::engine::general_purpose::STANDARD.encode(blob), ), ); } } Ok(serde_json::Value::Object(out)) }).await; match blk { Ok(Ok(v)) => HttpResponse::Ok().json(v), Ok(Err(e)) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// Shared multipart reader for WolfHA uploads (apply-delta and /// receive-seed): text fields into a map, the archive streamed to the /// staging dir (NOT /tmp — a multi-GB seed on a tmpfs is how the /// wolfstack-1 staging incident happened). async fn wolfha_read_multipart( payload: &mut actix_multipart::Multipart, ) -> Result< ( std::collections::HashMap, Option, Option, Option, ), String, > { use futures::StreamExt; let default_stage_dir = "/var/lib/wolfstack/wolfha"; std::fs::create_dir_all(default_stage_dir).map_err(|e| format!("staging dir: {}", e))?; let mut fields: std::collections::HashMap = std::collections::HashMap::new(); let mut archive_path: Option = None; let mut blockdelta_path: Option = None; let mut efivars_path: Option = None; while let Some(item) = payload.next().await { let mut field = item.map_err(|e| format!("multipart error: {}", e))?; let field_name = field.name().unwrap_or("").to_string(); // File parts stream straight to disk. `blockdelta` is usually // small, but "usually" is not a size limit — a rewritten multi-GB // file produces a delta to match, and buffering it would undo the // memory fix that put the archive on disk in the first place. // `efivars` is an OVMF NVRAM image (hundreds of KB) riding along // with VM seeds/deltas — binary, so it must never land in the // lossy text-field map. // A seed names the storage location its copy goes to (and how much // room it needs) in text fields sent BEFORE the archive: stage the // upload on that same drive, and refuse before writing a byte if it // won't fit — never fill a root disk mid-upload again (2026-11-23). let stage_dir = if field_name == "archive" { match fields.get("target_base").map(|s| s.trim()).filter(|s| !s.is_empty()) { Some(base) => { let base = crate::wolfha::storage::resolve_target(Some(base))?; let dir = crate::wolfha::storage::staging_dir(&base); std::fs::create_dir_all(&dir).map_err(|e| format!("staging dir: {}", e))?; if let Some(need) = fields.get("need_bytes").and_then(|n| n.trim().parse::().ok()) { crate::wolfha::storage::check_fits(&base, need, "This copy")?; } dir } None => default_stage_dir.to_string(), } } else { default_stage_dir.to_string() }; let staged = match field_name.as_str() { "archive" => Some(format!("{}/incoming-{}.tar.gz", stage_dir, uuid::Uuid::new_v4())), "blockdelta" => Some(format!("{}/incoming-{}.blocks", stage_dir, uuid::Uuid::new_v4())), "efivars" => Some(format!("{}/incoming-{}.fd", stage_dir, uuid::Uuid::new_v4())), _ => None, }; if let Some(path) = staged { let mut file = std::fs::File::create(&path).map_err(|e| format!("stage file: {}", e))?; use std::io::Write; while let Some(chunk) = field.next().await { let data = chunk.map_err(|e| format!("upload read: {}", e))?; file.write_all(&data).map_err(|e| format!("stage write: {}", e))?; } match field_name.as_str() { "archive" => archive_path = Some(path), "blockdelta" => blockdelta_path = Some(path), _ => efivars_path = Some(path), } } else { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } fields.insert(field_name, String::from_utf8_lossy(&buf).to_string()); } } Ok((fields, archive_path, blockdelta_path, efivars_path)) } /// POST /api/wolfha/apply-delta — a primary ships an incremental rootfs /// delta to this replica. pub async fn wolfha_apply_delta( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let (fields, archive, blockdelta, efivars) = match wolfha_read_multipart(&mut payload).await { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; // Container deltas never carry NVRAM — drop a stray part immediately. if let Some(v) = efivars { let _ = std::fs::remove_file(v); } let container = fields.get("container").map(|s| s.trim().to_string()).unwrap_or_default(); if container.is_empty() || !crate::auth::is_safe_name(&container) { if let Some(a) = archive { let _ = std::fs::remove_file(a); } if let Some(b) = blockdelta { let _ = std::fs::remove_file(b); } return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let deletions: Vec = fields.get("deletions") .and_then(|d| serde_json::from_str(d).ok()) .unwrap_or_default(); let config = fields.get("config").cloned().unwrap_or_default(); let ha_meta: Option = fields.get("ha_meta") .and_then(|m| serde_json::from_str(m).ok()); // Primary's mtime per block-delta file (absent from older primaries). let delta_mtimes: std::collections::HashMap = fields.get("delta_mtimes") .and_then(|m| serde_json::from_str(m).ok()) .unwrap_or_default(); let c = container.clone(); let archive_c = archive.clone(); let blockdelta_c = blockdelta.clone(); let blk = web::block(move || -> Result { let store = crate::wolfha::HaStore::load(); let entry = store.get(&c).ok_or_else(|| format!("'{}' is not a WolfHA copy on this node", c))?; // Deltas land on replicas — and on a STALE ex-primary, which is // exactly how a failback reverse-sync catches it up. if entry.role == crate::wolfha::HaRole::Primary && !entry.stale { return Err(format!("'{}' is the ACTIVE primary here — refusing a delta that would overwrite it", c)); } // Block deltas are applied BEFORE the tar. The tar carries whole // files, so if a path somehow appears in both, the whole-file copy // is the newer, more complete truth and must win. if let Some(b) = &blockdelta_c { crate::wolfha::apply_block_deltas(&c, b, &delta_mtimes)?; } let deleted = match &archive_c { Some(a) => crate::wolfha::apply_delta(&c, a, &deletions, &config)?, // No archive = metadata-only heartbeat: the sender's diff // proved the rootfs identical. Settings changes and the // freshness clock must not wait for a file to change // (found live 2026-08-08: idle containers never got either). // A round carrying only block deltas still needs the config // refresh, so this arm is reached in that case too. None => { crate::wolfha::refresh_replica_config(&c, &config); 0 } }; let mut store = crate::wolfha::HaStore::load(); if let Some(e) = store.get_mut(&c) { e.last_delta_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); // A completed round (delta or verified-identical heartbeat) // makes this copy an exact image of the sender — not stale. e.stale = false; // Settings ride along with every round: priority order, // witness, timings stay current on every standby. if let Some(m) = &ha_meta { m.apply_to(e); } let _ = store.save(); } Ok(deleted) }).await; if let Some(a) = &archive { let _ = std::fs::remove_file(a); } if let Some(b) = &blockdelta { let _ = std::fs::remove_file(b); } match blk { Ok(Ok(deleted)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "deleted": deleted })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/apply-vm-delta — a primary ships an incremental VM /// disk delta to this replica. /// /// The VM definition rides along with every delta: a replica holding a /// perfect disk image but no definition cannot start the VM on failover, /// and the definition can change between rounds. pub async fn wolfha_apply_vm_delta( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let (fields, archive, _blocks, efivars) = match wolfha_read_multipart(&mut payload).await { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let cleanup_staged = |a: &Option, v: &Option| { if let Some(p) = a { let _ = std::fs::remove_file(p); } if let Some(p) = v { let _ = std::fs::remove_file(p); } }; let container = fields.get("container").map(|s| s.trim().to_string()).unwrap_or_default(); if container.is_empty() || !crate::auth::is_safe_name(&container) { cleanup_staged(&archive, &efivars); return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid VM name"})); } let Some(archive) = archive else { cleanup_staged(&None, &efivars); return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a VM delta upload must carry the delta image" })); }; let ha_meta: Option = fields.get("ha_meta") .and_then(|m| serde_json::from_str(m).ok()); let vm_config: Option = fields.get("vm_config") .and_then(|c| serde_json::from_str(c).ok()); let chain_prev = fields.get("chain_prev").cloned().unwrap_or_default(); let chain_next = fields.get("chain_next").cloned().unwrap_or_default(); let (c, archive_c, efivars_c) = (container.clone(), archive.clone(), efivars.clone()); let blk = web::block(move || -> Result<(), String> { let store = crate::wolfha::HaStore::load(); let Some(entry) = store.get(&c) else { // No entry: this node lost (or never got) its copy. Carrying // the marker lets the primary heal it with a fresh full seed // instead of erroring forever. return Err(format!( "{}: '{}' is not a WolfHA copy on this node", crate::wolfha::VM_NEEDS_SEED, c )); }; if entry.role == crate::wolfha::HaRole::Primary && !entry.stale { // Deliberately NOT the needs-seed marker: two nodes both // believing they are the active primary is an operator // problem, and an automatic seed must never paper over it. return Err(format!( "'{}' is the ACTIVE primary here — refusing a delta that would overwrite it", c )); } // The VM definition first: the disk-path/NVRAM installs resolve // through the stored definition, and the primary's is current. if let Some(cfg) = &vm_config { crate::wolfha::vm_store_replica_config(&c, cfg)?; } crate::wolfha::vm_apply_delta(&c, &archive_c, &chain_prev, &chain_next, efivars_c.as_deref())?; let mut store = crate::wolfha::HaStore::load(); if let Some(e) = store.get_mut(&c) { e.last_delta_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); e.stale = false; if let Some(m) = &ha_meta { m.apply_to(e); } let _ = store.save(); } Ok(()) }).await; let _ = std::fs::remove_file(&archive); if let Some(v) = &efivars { let _ = std::fs::remove_file(v); } match blk { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/receive-seed — a primary installs the initial full /// copy on this node. pub async fn wolfha_receive_seed( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } if containers::is_proxmox() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "WolfHA replicas require a native (non-Proxmox) node — Proxmox guest storage is not a plain host path" })); } // A seed never carries a block-delta part; a VM seed may carry NVRAM. let (fields, archive, _no_blockdelta, efivars) = match wolfha_read_multipart(&mut payload).await { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let cleanup_staged = |a: &Option, v: &Option| { if let Some(p) = a { let _ = std::fs::remove_file(p); } if let Some(p) = v { let _ = std::fs::remove_file(p); } }; let container = fields.get("container").map(|s| s.trim().to_string()).unwrap_or_default(); if container.is_empty() || !crate::auth::is_safe_name(&container) { cleanup_staged(&archive, &efivars); return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let Some(archive) = archive else { cleanup_staged(&None, &efivars); return HttpResponse::BadRequest().json(serde_json::json!({"error": "archive is required"})); }; let config = fields.get("config").cloned().unwrap_or_default(); // Storage location the primary chose for this copy. Absent from older // primaries, which keeps the old behaviour (existing or default path). let target_base = fields.get("target_base").cloned().filter(|s| !s.trim().is_empty()); let wolfnet_ip = fields.get("wolfnet_ip").cloned().filter(|s| !s.is_empty()); let ha_meta: Option = fields.get("ha_meta") .and_then(|m| serde_json::from_str(m).ok()); let Some(primary) = fields.get("primary").and_then(|p| serde_json::from_str::(p).ok()) else { cleanup_staged(&Some(archive), &efivars); return HttpResponse::BadRequest().json(serde_json::json!({"error": "primary peer identity is required"})); }; // The primary states what it is seeding. An older primary sends no // `kind`, which defaults to Container — exactly what those primaries // have always been sending. let seed_kind = ha_meta.as_ref().map(|m| m.kind).unwrap_or_default(); let blk = if seed_kind == crate::wolfha::SubjectKind::Vm { // A VM seed is a full qcow2 plus the VM definition and the chain // token every later delta will be verified against. let Some(vm_config) = fields.get("vm_config") .and_then(|c| serde_json::from_str::(c).ok()) else { cleanup_staged(&Some(archive), &efivars); return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a VM seed must carry the VM definition (vm_config)" })); }; let chain = fields.get("chain").cloned().unwrap_or_default(); let (c, archive_c, efivars_c) = (container.clone(), archive.clone(), efivars.clone()); web::block(move || { crate::wolfha::install_vm_seed( &c, &archive_c, &vm_config, primary, ha_meta.as_ref(), &chain, efivars_c.as_deref(), ) }).await } else { let (c, archive_c) = (container.clone(), archive.clone()); web::block(move || { crate::wolfha::install_seed( &c, seed_kind, &archive_c, &config, primary, wolfnet_ip.as_deref(), ha_meta.as_ref(), target_base.as_deref(), ) }).await }; // install_vm_seed consumes the archive by rename when it can — remove // is a no-op then, and the cleanup that matters on every error path. let _ = std::fs::remove_file(&archive); if let Some(v) = &efivars { let _ = std::fs::remove_file(v); } match blk { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// Ask a standby for its container storage locations and free space. async fn wolfha_peer_storage( peer: &crate::wolfha::HaPeer, secret: &str, ) -> Result, String> { let client = &*API_HTTP_CLIENT; let mut last_err = String::from("unreachable"); for url in build_node_urls(&peer.address, peer.port, "/api/wolfha/storage") { match client.get(&url) .timeout(std::time::Duration::from_secs(15)) .peer_auth(secret) .send().await { Ok(r) if r.status().is_success() => { let v: serde_json::Value = r.json().await.map_err(|e| e.to_string())?; return serde_json::from_value(v.get("options").cloned().unwrap_or_default()) .map_err(|e| format!("unreadable storage list: {}", e)); } Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => { let _ = r.bytes().await; return Err("its WolfStack is too old to report free space — upgrade it first".to_string()); } Ok(r) => { last_err = format!("HTTP {}", r.status().as_u16()); let _ = r.bytes().await; } Err(e) => last_err = e.to_string(), } } Err(last_err) } /// Check a standby has room for a VM seed: the staged image, and the disk /// it becomes in the same folder as on this node — twice the size when both /// sit on one drive. async fn wolfha_peer_vm_room( peer: &crate::wolfha::HaPeer, secret: &str, disk_dir: &str, size: u64, ) -> Result<(), String> { use crate::wolfha::storage::{gb, HEADROOM_BYTES}; let client = &*API_HTTP_CLIENT; let q = format!("/api/wolfha/storage?path={}", urlencoding::encode(disk_dir)); let mut last_err = String::from("unreachable"); for url in build_node_urls(&peer.address, peer.port, &q) { match client.get(&url).timeout(std::time::Duration::from_secs(15)).peer_auth(secret).send().await { Ok(r) if r.status().is_success() => { let v: serde_json::Value = r.json().await.map_err(|e| e.to_string())?; let free = |k: &str| v.get(k).and_then(|x| x.get("free_bytes")).and_then(|x| x.as_u64()); let dev = |k: &str| v.get(k).and_then(|x| x.get("device")).and_then(|x| x.as_u64()); let (Some(disk_free), Some(stage_free)) = (free("path"), free("vm_staging")) else { return Err("it did not report free space for the VM's disk folder".to_string()); }; let same_drive = dev("path").is_some() && dev("path") == dev("vm_staging"); let want = |n: u64| n.saturating_add(HEADROOM_BYTES); return if same_drive { if disk_free >= want(size.saturating_mul(2)) { Ok(()) } else { Err(format!("the copy needs {} on the drive holding {} (staged image + disk, plus {} kept free) but only {} is free", gb(size.saturating_mul(2)), disk_dir, gb(HEADROOM_BYTES), gb(disk_free))) } } else if disk_free < want(size) { Err(format!("the disk needs {} in {} (plus {} kept free) but only {} is free", gb(size), disk_dir, gb(HEADROOM_BYTES), gb(disk_free))) } else if stage_free < want(size) { Err(format!("staging the image needs {} in {} (plus {} kept free) but only {} is free", gb(size), crate::wolfha::storage::VM_STAGE_DIR, gb(HEADROOM_BYTES), gb(stage_free))) } else { Ok(()) }; } Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => { let _ = r.bytes().await; return Err("its WolfStack is too old to report free space — upgrade it first".to_string()); } Ok(r) => { last_err = format!("HTTP {}", r.status().as_u16()); let _ = r.bytes().await; } Err(e) => last_err = e.to_string(), } } Err(last_err) } /// The storage location a standby's copy goes to: the requested one, else /// the standby's default (most free space) — and only if it fits. fn wolfha_pick_storage( opts: &[crate::wolfha::storage::StorageOption], requested: Option<&str>, need: u64, ) -> Result { use crate::wolfha::storage::{gb, HEADROOM_BYTES}; let requested = requested.map(str::trim).filter(|s| !s.is_empty()); let chosen = match requested { Some(r) => opts.iter().find(|o| o.path.trim_end_matches('/') == r.trim_end_matches('/')) .ok_or_else(|| format!("'{}' is not one of its storage locations", r))?, None => opts.iter().find(|o| o.default) .ok_or_else(|| "it has no container storage location".to_string())?, }; if chosen.free_bytes >= need.saturating_add(HEADROOM_BYTES) { return Ok(chosen.path.clone()); } let others: Vec = opts.iter() .filter(|o| o.path != chosen.path && o.free_bytes >= need.saturating_add(HEADROOM_BYTES)) .map(|o| format!("{} ({} free)", o.path, gb(o.free_bytes))) .collect(); Err(format!( "the copy needs {} on {} (plus {} kept free) but only {} is free there{}", gb(need), chosen.path, gb(HEADROOM_BYTES), gb(chosen.free_bytes), if others.is_empty() { " — no storage location on it has room".to_string() } else { format!(" — pick {} instead", others.join(" or ")) })) } #[derive(Deserialize)] pub struct WolfHaStorageQuery { /// Optional extra path to report free space for (a VM's disk folder). #[serde(default)] pub path: Option, } /// GET /api/wolfha/storage — this node's container storage locations with /// free space (the Protect dialog's "store the copy on" list, and the /// primary's pre-seed space check). Operator session or cluster secret. pub async fn wolfha_storage( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if wolfha_peer_auth(&req, &state).is_err() && let Err(resp) = require_auth(&req, &state) { return resp; } let path = query.path.clone().filter(|p| p.starts_with('/')); let res = web::block(move || { let options = crate::wolfha::storage::storage_options(); let space = |p: String| crate::wolfha::storage::fs_space(&p).map(|(f, t)| serde_json::json!({ "path": p.clone(), "free_bytes": f, "total_bytes": t, "device": crate::wolfha::storage::fs_device(&p), })); let path_space = path.and_then(space); let vm_staging = space(crate::wolfha::storage::VM_STAGE_DIR.to_string()); serde_json::json!({ "options": options, "path": path_space, "vm_staging": vm_staging, "headroom_bytes": crate::wolfha::storage::HEADROOM_BYTES, }) }).await; match res { Ok(v) => HttpResponse::Ok().json(v), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(Deserialize)] pub struct WolfHaEnableReq { pub container: String, /// Container (default) or VM. Absent in requests from older clients, /// which only ever protected containers. #[serde(default)] pub kind: crate::wolfha::SubjectKind, /// Ordered — the sequence IS the failover priority. pub replica_node_ids: Vec, #[serde(default)] pub interval_minutes: u64, #[serde(default)] pub auto_failover: bool, #[serde(default)] pub witness: String, #[serde(default)] pub failover_after_secs: u64, /// Standby node id → the storage location (one of that node's /// registered LXC paths) its copy goes to. A standby not listed gets the /// location with the most free space. Containers only — a VM copy keeps /// the storage path its definition names. #[serde(default)] pub storage: std::collections::HashMap, } /// Validate the auto-failover settings shared by enable and update. /// Returns the normalised (witness, failover_after_secs). fn wolfha_validate_auto( auto_failover: bool, witness: &str, failover_after_secs: u64, ) -> Result<(String, u64), String> { let witness = witness.trim().to_string(); if auto_failover { if witness.is_empty() { return Err("automatic failover needs a witness IP (normally your gateway) — a node only acts while it can ping the witness".to_string()); } if !crate::auth::is_safe_name(&witness) || witness.parse::().is_err() && !witness.contains('.') { return Err(format!("'{}' does not look like a witness IP or hostname", witness)); } } let after = if failover_after_secs == 0 { 90 } else { failover_after_secs.max(30) }; Ok((witness, after)) } /// GET /api/wolfha/witness-hint?container=NAME — suggest a witness IP /// for the auto-failover setting, derived from the container being /// protected: its own configured gateway (`lxc.net.0.ipv4.gateway`) /// when it has a static one, else this host's default gateway — the /// same router the container's traffic already depends on, which is /// exactly what a witness should be (Paul, 2026-08-11: "you should be /// able to work it out from the container we're protecting"). pub async fn wolfha_witness_hint( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = query.get("container").map(|s| s.trim()).unwrap_or(""); if !container.is_empty() && crate::auth::is_safe_name(container) { let config_path = format!("{}/{}/config", containers::lxc_base_dir(container), container); if let Ok(cfg) = std::fs::read_to_string(&config_path) { for line in cfg.lines() { let Some((k, v)) = line.split_once('=') else { continue }; if k.trim() == "lxc.net.0.ipv4.gateway" { let v = v.trim(); // "auto" = borrow the bridge address at start — not // a pingable address to suggest. if !v.is_empty() && v != "auto" { return HttpResponse::Ok().json(serde_json::json!({ "suggestion": v, "source": "container gateway", })); } } } } } match default_gateway_ip() { Some(gw) => HttpResponse::Ok().json(serde_json::json!({ "suggestion": gw.to_string(), "source": "this node's gateway", })), None => HttpResponse::Ok().json(serde_json::json!({ "suggestion": null })), } } /// Containers with a protect (seed) currently running on this node. /// The HaStore entry only appears AFTER a successful seed, so without /// this a second Protect click during the (long) rootfs tar started a /// second parallel snapshot of the same container — two 43 GB tars on /// legolas/wolfstack-3, 2026-08-11. static WOLFHA_ENABLE_INFLIGHT: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new())); /// Live + failed protect attempts, keyed by container — what the /// WolfHA list shows for a container that has no HaStore entry yet. /// A protect used to be invisible until it succeeded (the entry is /// only written after seeding) and a failure was just a 10-second /// toast — Paul went back to the list mid-seed and found "nothing in /// the list" (2026-08-11). In-memory on purpose: a daemon restart /// aborts the seed anyway, and stale "seeding" rows that outlive /// their task would be worse than a clean slate. static WOLFHA_PROTECT_ATTEMPTS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); #[derive(Clone, Serialize)] struct WolfHaProtectAttempt { /// Latest human-readable stage ("Creating live rootfs snapshot…", /// "Seeding replica 1/2 on …"). message: String, /// Set when the attempt failed — the row persists (until dismissed /// or retried) so the operator finds out even after the toast is /// long gone. error: Option, updated_at: u64, } fn wolfha_attempts_lock() -> std::sync::MutexGuard<'static, std::collections::HashMap> { match WOLFHA_PROTECT_ATTEMPTS.lock() { Ok(g) => g, Err(p) => p.into_inner(), } } fn wolfha_protect_note(container: &str, message: &str) { wolfha_attempts_lock().insert(container.to_string(), WolfHaProtectAttempt { message: message.to_string(), error: None, updated_at: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0), }); } fn wolfha_protect_fail(container: &str, error: &str) { wolfha_attempts_lock().insert(container.to_string(), WolfHaProtectAttempt { message: "Protect failed".into(), error: Some(error.to_string()), updated_at: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0), }); } fn wolfha_protect_clear(container: &str) { wolfha_attempts_lock().remove(container); } /// Removes its container from [`WOLFHA_ENABLE_INFLIGHT`] on drop, so /// every exit path of the seed task — success, failure, panic — /// releases the slot. struct WolfHaInflightGuard(String); impl Drop for WolfHaInflightGuard { fn drop(&mut self) { let mut set = match WOLFHA_ENABLE_INFLIGHT.lock() { Ok(g) => g, Err(p) => p.into_inner(), }; set.remove(&self.0); } } /// POST /api/wolfha/enable — protect a container: seed every chosen /// replica node, take over the autostart flag, record the entry. /// Runs on the node hosting the container (UI proxies to it). pub async fn wolfha_enable( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); let subject_kind = body.kind; if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let is_pve = subject_kind == crate::wolfha::SubjectKind::PveContainer; if containers::is_proxmox() && !is_pve { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "this node is Proxmox-managed — protect its containers as \"Proxmox container (ZFS)\", the native LXC and VM paths need a native node" })); } if is_pve && !containers::is_proxmox() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a Proxmox container can only be protected from the Proxmox host it runs on" })); } if is_pve && !crate::wolfha::replication::zfs_send::is_vmid(&container) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a Proxmox container is identified by its numeric VMID" })); } let base = containers::lxc_base_dir(&container); let container_dir = format!("{}/{}", base, container); let rootfs = format!("{}/rootfs", container_dir); if is_pve { if !std::path::Path::new(&crate::wolfha::pve_config_path(&container)).exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("Proxmox container {} not found on this node", container) })); } } else if subject_kind == crate::wolfha::SubjectKind::Vm { let vm = container.clone(); match web::block(move || -> Result<(), String> { // What CAN'T fail over is refused up front, honestly, instead // of seeding a replica that dies at promotion: // - extra disks: replication covers the OS disk (the one the // dirty bitmap tracks) — a promoted copy silently missing // a data disk is worse than no HA; // - passthrough hardware is physically attached to THIS host; // - a TPM's swtpm state holds sealing secrets that are not // replicated (and must not travel in a sync stream) — a // promoted Windows/BitLocker guest without them can't boot. let (_, cfg) = crate::wolfha::vm_disk_and_config(&vm)?; if !cfg.extra_disks.is_empty() { return Err("this VM has extra data disks, and WolfHA replicates only the OS disk — a failover would lose them. Detach them (or keep their data on network storage) to protect this VM".to_string()); } if !cfg.pci_devices.is_empty() || !cfg.usb_devices.is_empty() { return Err("this VM uses PCI/USB passthrough — hardware attached to this host can't fail over to another node".to_string()); } if cfg.tpm { return Err("this VM has an emulated TPM, whose state (BitLocker-relevant sealing keys) is not replicated — a promoted copy could not unseal its disks".to_string()); } // Attach the dirty bitmap BEFORE anything else. Every write // from this instant is captured, so the first incremental // after the seed carries whatever changed while the seed was // being taken — do it later and those writes are in no delta // at all and the replica starts life already diverged. crate::wolfha::vm_begin_tracking(&vm) }).await { Ok(Ok(())) => {} Ok(Err(e)) => { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("cannot protect this VM: {}", e) })); } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })); } } } else if !std::path::Path::new(&rootfs).is_dir() { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("container '{}' (with a directory rootfs) not found on this node", container) })); } if crate::wolfha::HaStore::load().get(&container).is_some() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("'{}' is already WolfHA-managed on this node", container) })); } if body.replica_node_ids.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "pick at least one replica node"})); } // Claim the in-flight slot BEFORE spawning; the guard travels into // the task and releases on any exit. { let mut inflight = match WOLFHA_ENABLE_INFLIGHT.lock() { Ok(g) => g, Err(p) => p.into_inner(), }; if !inflight.insert(container.clone()) { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!("a protect of '{}' is already running on this node — watch its progress toast, or wait for it to finish", container) })); } } let inflight_guard = WolfHaInflightGuard(container.clone()); let self_peer = match wolfha_self_peer(&state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let mut peers: Vec = Vec::new(); for id in &body.replica_node_ids { let Some(node) = state.cluster.get_node(id) else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("replica node '{}' is not in this cluster", id) })); }; if node.is_self { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "a container can't replicate to its own node" })); } if node.node_type == "proxmox" { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("node '{}' is a Proxmox API node that is not running WolfStack — a standby must run WolfStack (install it on that host to use it)", node.hostname) })); } peers.push(crate::wolfha::HaPeer { node_id: node.id, address: node.address, port: node.port }); } let interval = if body.interval_minutes == 0 { 5 } else { body.interval_minutes }; let (witness, failover_after) = match wolfha_validate_auto(body.auto_failover, &body.witness, body.failover_after_secs) { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let auto_failover = body.auto_failover; let storage_req = body.storage.clone(); let tasks = state.migration_tasks.clone(); let task_id = migration_create(&tasks); migration_update(&tasks, &task_id, "seed", "Preparing initial replica seed…"); wolfha_protect_note(&container, "Preparing initial replica seed…"); let tid = task_id.clone(); let secret = state.cluster_secret.clone(); let enable_cluster = state.cluster.clone(); tokio::spawn(async move { // Holds the per-container protect slot for the life of this // task — released by Drop on every exit path. let _inflight_guard = inflight_guard; if subject_kind == crate::wolfha::SubjectKind::PveContainer { wolfha_enable_pve(container, peers, interval, auto_failover, witness, failover_after, self_peer, secret, enable_cluster, tasks, tid).await; return; } // One live full tar of the rootfs, shipped to every replica. The // container keeps running — the copy is crash-consistent and the // first delta rounds true it up. let stage_dir = "/var/lib/wolfstack/wolfha"; if let Err(e) = std::fs::create_dir_all(stage_dir) { if subject_kind == crate::wolfha::SubjectKind::Vm { let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; } wolfha_protect_fail(&container, &format!("staging dir: {}", e)); migration_fail(&tasks, &tid, &format!("staging dir: {}", e)); return; } // ── VM subject: full disk image + definition + chain token ── // Fully separate from the rootfs-tar pipeline below — feeding a VM // into that is exactly the released bug this replaces (tar of // /var/lib/lxc//rootfs, which does not exist). Every failure // exit detaches the dirty bitmap the gate attached, so a failed // protect leaves no replication state inside the operator's image. // Source: this function's container pipeline below (tar → per-peer // POST /api/wolfha/receive-seed → HaStore entry) — mirrored per // stage with the VM primitives from src/wolfha/mod.rs. if subject_kind == crate::wolfha::SubjectKind::Vm { migration_update(&tasks, &tid, "seed", "Creating a full disk image (the VM keeps running)…"); wolfha_protect_note(&container, "Creating a full disk image (the VM keeps running)…"); let vm = container.clone(); let seed = tokio::task::spawn_blocking(move || crate::wolfha::vm_take_seed(&vm)).await; let (seed_path, seed_size, vm_cfg) = match seed.map_err(|e| e.to_string()).and_then(|r| r) { Ok(v) => v, Err(e) => { let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; wolfha_protect_fail(&container, &format!("Seed snapshot failed: {}", e)); migration_fail(&tasks, &tid, &format!("Seed snapshot failed: {}", e)); return; } }; let cfg_json = match serde_json::to_string(&vm_cfg) { Ok(j) => j, Err(e) => { let _ = std::fs::remove_file(&seed_path); let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; wolfha_protect_fail(&container, &format!("VM definition would not serialize: {}", e)); migration_fail(&tasks, &tid, &format!("VM definition would not serialize: {}", e)); return; } }; // The seed token — every replica's copy of this image gets it, // and the first delta will name it as the base it fits. let chain = uuid::Uuid::new_v4().to_string(); let ha_meta_json = serde_json::to_string(&crate::wolfha::HaMeta { kind: subject_kind, interval_minutes: interval, replicas: peers.clone(), auto_failover, witness: witness.clone(), failover_after_secs: failover_after, primary: Some(self_peer.clone()), zfs_datasets: Vec::new(), bind_requirements: Vec::new(), }).unwrap_or_default(); let size_mb = seed_size / (1024 * 1024); // Room on every standby, checked before the first byte is sent. let disk_dir = crate::vms::manager::VmManager::new().os_disk_path_for(&vm_cfg) .parent().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(); for peer in &peers { if let Err(e) = wolfha_peer_vm_room(peer, &secret, &disk_dir, seed_size).await { let _ = std::fs::remove_file(&seed_path); let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; wolfha_protect_fail(&container, &format!("Not protected — {}: {}", peer.node_id, e)); migration_fail(&tasks, &tid, &format!("Not protected — {}: {}", peer.node_id, e)); return; } } for (i, peer) in peers.iter().enumerate() { migration_update(&tasks, &tid, "seed", &format!("Seeding replica {}/{} on {} ({} MB)…", i + 1, peers.len(), peer.node_id, size_mb)); wolfha_protect_note(&container, &format!("Seeding replica {}/{} on {} ({} MB)…", i + 1, peers.len(), peer.node_id, size_mb)); if let Err(e) = crate::wolfha::vm_seed_replica( &container, peer, &secret, &crate::wolfha::VmSeedPayload { seed_path: &seed_path, vm_config_json: &cfg_json, chain: &chain, primary: &self_peer, ha_meta_json: &ha_meta_json, }, ).await { let _ = std::fs::remove_file(&seed_path); let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; wolfha_protect_fail(&container, &format!( "Seeding replica on {} failed: {}. No HA entry was created — fix the node and try again.", peer.node_id, e)); migration_fail(&tasks, &tid, &format!( "Seeding replica on {} failed: {}. No HA entry was created — fix the node and enable again.", peer.node_id, e)); return; } } let _ = std::fs::remove_file(&seed_path); // Boot takeover, VM-style: strip `auto_start` so autostart_vms() // can never race the boot-guard takeover check; the flag is // remembered in the entry and restored when HA is disabled. let had_autostart = vm_cfg.auto_start; if had_autostart { let vm = container.clone(); if let Ok(Err(e)) = tokio::task::spawn_blocking(move || crate::wolfha::vm_set_autostart(&vm, false)).await { tracing::warn!("wolfha[{}]: could not strip the VM autostart flag: {}", container, e); } } let mut store = crate::wolfha::HaStore::load(); store.remove(&container); store.entries.push(crate::wolfha::HaEntry { container: container.clone(), kind: subject_kind, role: crate::wolfha::HaRole::Primary, interval_minutes: interval, replicas: peers.clone(), primary: None, autostart_managed: had_autostart, last_sync: std::collections::HashMap::new(), last_delta_at: 0, stale: false, pending_vm_delta: None, vm_chain: Some(chain), auto_failover, witness: witness.clone(), failover_after_secs: failover_after, self_identity: Some(self_peer.clone()), zfs_datasets: Vec::new(), bind_requirements: Vec::new(), }); if let Err(e) = store.save() { let vm = container.clone(); let _ = tokio::task::spawn_blocking(move || crate::wolfha::vm_end_tracking(&vm)).await; wolfha_protect_fail(&container, &format!("Replicas seeded but saving the HA entry failed: {}", e)); migration_fail(&tasks, &tid, &format!("Replicas seeded but saving the HA entry failed: {}", e)); return; } wolfha_protect_clear(&container); migration_done(&tasks, &tid, &format!( "'{}' is protected — {} replica(s) seeded, disk delta sync every {} min.", container, peers.len(), interval)); return; } // ── Room for the copy, checked BEFORE packing ── // Every standby is asked where its copy goes and whether it fits; // this node checks it has room to pack. Any "no" stops here, before // an hour of packing and a multi-GB upload (2026-11-23: a 172 GB // copy filled a standby's root disk mid-unpack). migration_update(&tasks, &tid, "seed", "Measuring the container to check every standby has room…"); wolfha_protect_note(&container, "Measuring the container to check every standby has room…"); let rootfs_m = rootfs.clone(); let rootfs_bytes = match tokio::task::spawn_blocking(move || crate::wolfha::storage::dir_bytes(&rootfs_m)).await .map_err(|e| e.to_string()).and_then(|r| r) { Ok(b) => b, Err(e) => { wolfha_protect_fail(&container, &format!("Could not measure the container: {}", e)); migration_fail(&tasks, &tid, &format!("Could not measure the container: {}", e)); return; } }; let need = crate::wolfha::storage::seed_need_bytes(rootfs_bytes); let mut targets: std::collections::HashMap = std::collections::HashMap::new(); for peer in &peers { let chosen = match wolfha_peer_storage(peer, &secret).await { Ok(opts) => wolfha_pick_storage(&opts, storage_req.get(&peer.node_id).map(|s| s.as_str()), need) .map_err(|e| format!("{}: {}", peer.node_id, e)), Err(e) => Err(format!( "could not check free space on {}: {} — nothing was packed or sent", peer.node_id, e)), }; match chosen { Ok(path) => { targets.insert(peer.node_id.clone(), path); } Err(e) => { wolfha_protect_fail(&container, &format!("Not protected — {}", e)); migration_fail(&tasks, &tid, &format!("Not protected — {}", e)); return; } } } // Pack on whichever local storage location has the most room — // never the root disk by default. let local_stage = match tokio::task::spawn_blocking(move || -> Result { let base = crate::wolfha::storage::resolve_target(None)?; crate::wolfha::storage::check_fits(&base, rootfs_bytes, "Packing the first copy on this node")?; let dir = crate::wolfha::storage::staging_dir(&base); std::fs::create_dir_all(&dir).map_err(|e| format!("staging dir: {}", e))?; Ok(dir) }).await.map_err(|e| e.to_string()).and_then(|r| r) { Ok(d) => d, Err(e) => { wolfha_protect_fail(&container, &format!("Not protected — {}", e)); migration_fail(&tasks, &tid, &format!("Not protected — {}", e)); return; } }; let archive = format!("{}/seed-{}.tar.gz", local_stage, uuid::Uuid::new_v4()); migration_update(&tasks, &tid, "seed", "Creating live rootfs snapshot…"); wolfha_protect_note(&container, "Creating live rootfs snapshot…"); let (rootfs_c, archive_c) = (rootfs.clone(), archive.clone()); // Packing a large rootfs takes many minutes (an 11 GB one sat on // one unchanging line long enough to look hung — 2026-11-22), so // report the compressed size as it grows. let mut tar = tokio::task::spawn_blocking(move || crate::wolfha::tar_full_rootfs(&rootfs_c, &archive_c)); let tar_res = loop { tokio::select! { r = &mut tar => break r, _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => { let mb = tokio::fs::metadata(&archive).await.map(|m| m.len() / (1024 * 1024)).unwrap_or(0); let msg = format!("Packing the rootfs for the first copy — {} MB compressed so far (the container keeps running)…", mb); migration_update(&tasks, &tid, "seed", &msg); wolfha_protect_note(&container, &msg); } } }; if let Err(e) = tar_res.map_err(|e| e.to_string()).and_then(|r| r) { let _ = std::fs::remove_file(&archive); wolfha_protect_fail(&container, &format!("Seed snapshot failed: {}", e)); migration_fail(&tasks, &tid, &format!("Seed snapshot failed: {}", e)); return; } // The archive stays on disk and streams from there per attempt. // The old code read the whole thing into RAM and cloned it per // URL — a 43 GB rootfs produced a >15 GB allocation on a // production node with 20 GB free (legolas/wolfstack-3, // 2026-08-11). Never buffer a rootfs archive in memory. let size_mb = std::fs::metadata(&archive).map(|m| m.len() / (1024 * 1024)).unwrap_or(0); let config = std::fs::read_to_string(format!("{}/config", container_dir)).unwrap_or_default(); let wolfnet_ip = containers::lxc_get_wolfnet_ip(&container).unwrap_or_default(); let primary_json = serde_json::to_string(&self_peer).unwrap_or_default(); // Where each bind-mount source lives here — seeded with the copy so // a standby's preflight can judge it before the first sync round. let bind_requirements = { let cfg = config.clone(); tokio::task::spawn_blocking(move || crate::wolfha::binds::plan_requirements_live(&cfg)) .await .unwrap_or_default() }; let ha_meta_json = serde_json::to_string(&crate::wolfha::HaMeta { kind: subject_kind, interval_minutes: interval, replicas: peers.clone(), auto_failover, witness: witness.clone(), failover_after_secs: failover_after, primary: Some(self_peer.clone()), zfs_datasets: Vec::new(), bind_requirements: bind_requirements.clone(), }).unwrap_or_default(); let client = &*API_HTTP_CLIENT; for (i, peer) in peers.iter().enumerate() { migration_update(&tasks, &tid, "seed", &format!("Seeding replica {}/{} on {} ({} MB)…", i + 1, peers.len(), peer.node_id, size_mb)); wolfha_protect_note(&container, &format!("Seeding replica {}/{} on {} ({} MB)…", i + 1, peers.len(), peer.node_id, size_mb)); let urls = build_node_urls(&peer.address, peer.port, "/api/wolfha/receive-seed"); let mut last_err = String::new(); let mut ok = false; for url in &urls { // Fresh streaming part per attempt — the archive is read // from disk as it uploads, never buffered. let sent = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); let part = match crate::wolfha::stream_archive_part_counted(&archive, Some(sent.clone())).await { Ok(p) => p, Err(e) => { let _ = std::fs::remove_file(&archive); wolfha_protect_fail(&container, &format!("Seed archive vanished mid-send: {}", e)); migration_fail(&tasks, &tid, &format!("Seed archive vanished mid-send: {}", e)); return; } }; let form = reqwest::multipart::Form::new() .text("container", container.clone()) .text("config", config.clone()) .text("primary", primary_json.clone()) .text("wolfnet_ip", wolfnet_ip.clone()) .text("ha_meta", ha_meta_json.clone()) // Sent before the archive: the standby stages the upload // on this drive and checks the room before writing. .text("target_base", targets.get(&peer.node_id).cloned().unwrap_or_default()) .text("need_bytes", need.to_string()) .part("archive", part.file_name("seed.tar.gz")); let send = client.post(url) .peer_auth(secret.clone()) .timeout(std::time::Duration::from_secs(3600)) .multipart(form) .send(); tokio::pin!(send); // A seed upload runs for minutes; without this the status // sat on one line and looked hung (2026-11-22). Once every // byte is sent the standby is unpacking before it answers. let resp = loop { tokio::select! { r = &mut send => break r, _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => { let mb = sent.load(std::sync::atomic::Ordering::Relaxed) / (1024 * 1024); let msg = if mb >= size_mb { format!("Seeding replica {}/{} on {} — all {} MB sent, unpacking it there…", i + 1, peers.len(), peer.node_id, size_mb) } else { format!("Seeding replica {}/{} on {} — {} of {} MB sent…", i + 1, peers.len(), peer.node_id, mb, size_mb) }; migration_update(&tasks, &tid, "seed", &msg); wolfha_protect_note(&container, &msg); } } }; match resp { Ok(r) if r.status().is_success() => { ok = true; break; } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); last_err = format!("{}: HTTP {} {}", url, status, body.chars().take(300).collect::()); } Err(e) => { last_err = format!("{}: {}", url, e); } } } if !ok { let _ = std::fs::remove_file(&archive); wolfha_protect_fail(&container, &format!( "Seeding replica on {} failed: {}. No HA entry was created — fix the node and try again.", peer.node_id, last_err)); migration_fail(&tasks, &tid, &format!( "Seeding replica on {} failed: {}. No HA entry was created — fix the node and enable again.", peer.node_id, last_err)); return; } } // Every replica seeded — the staged archive is done with. let _ = std::fs::remove_file(&archive); // Take over the boot: WolfHA starts this container after the // takeover check, so lxc-autostart must not see the flag. let had_autostart = std::fs::read_to_string(format!("{}/config", container_dir)) .map(|c| c.lines().any(|l| l.trim() == "lxc.start.auto = 1")) .unwrap_or(false); // A VM needs its dirty bitmap attached before it is protected, so // every write from this point is captured. Doing it here — after // the seed has been taken — would miss writes made during the // seed, so `wolfha_enable` calls `vm_begin_tracking` earlier; this // is the container-only autostart takeover. if had_autostart { let _ = containers::lxc_set_autostart(&container, false); } let mut store = crate::wolfha::HaStore::load(); store.remove(&container); store.entries.push(crate::wolfha::HaEntry { container: container.clone(), kind: subject_kind, role: crate::wolfha::HaRole::Primary, interval_minutes: interval, replicas: peers.clone(), primary: None, autostart_managed: had_autostart, last_sync: std::collections::HashMap::new(), last_delta_at: 0, stale: false, pending_vm_delta: None, // Containers prove convergence via the per-round manifest // diff — no chain needed. vm_chain: None, auto_failover, witness: witness.clone(), failover_after_secs: failover_after, self_identity: Some(self_peer.clone()), zfs_datasets: Vec::new(), bind_requirements, }); if let Err(e) = store.save() { wolfha_protect_fail(&container, &format!("Replicas seeded but saving the HA entry failed: {}", e)); migration_fail(&tasks, &tid, &format!("Replicas seeded but saving the HA entry failed: {}", e)); return; } // The real HaStore entry exists now — the attempt row hands over. wolfha_protect_clear(&container); migration_done(&tasks, &tid, &format!( "'{}' is protected — {} replica(s) seeded, delta sync every {} min.", container, peers.len(), interval)); }); HttpResponse::Ok().json(serde_json::json!({ "task_id": task_id })) } #[derive(Deserialize)] pub struct WolfHaContainerReq { pub container: String, #[serde(default)] pub remove_replicas: bool, } #[derive(Deserialize)] pub struct WolfHaUpdateReq { pub container: String, pub interval_minutes: Option, pub auto_failover: Option, pub witness: Option, pub failover_after_secs: Option, } /// POST /api/wolfha/update — change a protected container's settings on /// its primary. Standbys pick the change up with the next delta (the /// HaMeta rides along), so no separate push is needed. pub async fn wolfha_update( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let mut store = crate::wolfha::HaStore::load(); let Some(entry) = store.get_mut(&container) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("'{}' is not WolfHA-managed on this node", container) })); }; if entry.role != crate::wolfha::HaRole::Primary || entry.stale { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "settings are changed on the active primary" })); } let new_auto = body.auto_failover.unwrap_or(entry.auto_failover); let new_witness = body.witness.clone().unwrap_or_else(|| entry.witness.clone()); let new_after = body.failover_after_secs.unwrap_or(entry.failover_after_secs); let (witness, after) = match wolfha_validate_auto(new_auto, &new_witness, new_after) { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; entry.auto_failover = new_auto; entry.witness = witness; entry.failover_after_secs = after; if let Some(iv) = body.interval_minutes { entry.interval_minutes = iv.max(1); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": "Settings saved — standbys receive them with the next sync round.", })) } /// POST /api/wolfha/sync — run a delta round now (primary only). pub async fn wolfha_sync_now( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // Reject before spawning so the operator sees WHY nothing will sync, // not a "started" toast followed by silence. { let store = crate::wolfha::HaStore::load(); match store.get(&container) { None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("'{}' is not WolfHA-managed on this node", container) })), Some(e) if e.role != crate::wolfha::HaRole::Primary || e.stale => { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("'{}' is not the active primary here — syncs run from the active node", container) })); } Some(_) => {} } } if !crate::wolfha::try_begin_sync(&container) { return HttpResponse::Ok().json(serde_json::json!({ "message": "a sync round is already running for this container" })); } let c = container.clone(); let cluster = state.cluster.clone(); tokio::spawn(async move { if let Err(e) = crate::wolfha::sync_container_now(&c, &cluster).await { tracing::warn!("wolfha: manual sync of '{}': {}", c, e); } crate::wolfha::end_sync(&c); }); HttpResponse::Ok().json(serde_json::json!({ "message": "sync started — status appears per replica as each finishes" })) } #[derive(Deserialize)] pub struct WolfHaDemoteReq { pub container: String, pub new_primary: crate::wolfha::HaPeer, #[serde(default)] pub final_sync: bool, } /// POST /api/wolfha/demote — called by a promoting peer (or the /// operator): stop the container here, optionally push one final /// quiesced delta to the new primary, then become its stale replica. pub async fn wolfha_demote( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let mut new_primary = body.new_primary.clone(); let final_sync = body.final_sync; let kind = crate::wolfha::HaStore::load().get(&container).map(|e| e.kind).unwrap_or_default(); // The address the promoting node advertised may not route from here // (it reports its registry self-address). The connection this request // arrived on proves its source IP does, so it is a candidate too. The // first that answers becomes the address the final delta goes to AND // the one recorded as this copy's new primary — so a later failback // from here reaches it rather than declaring it dead. { let mut cands: Vec<(String, u16)> = vec![(new_primary.address.clone(), new_primary.port)]; if let Some(ip) = peer_ip(&req) { cands.push((ip.to_string(), new_primary.port)); } for c in crate::wolfha::peer_addresses(&state.cluster, &new_primary) { if !cands.contains(&c) { cands.push(c); } } if let Some((a, p)) = crate::wolfha::first_reachable(&cands).await && (a != new_primary.address || p != new_primary.port) { tracing::info!("wolfha[{}]: new primary {} advertised {}:{}, reachable at {}:{} — using that", container, new_primary.node_id, new_primary.address, new_primary.port, a, p); new_primary.address = a; new_primary.port = p; } } let mut final_sync_note = String::new(); if kind == crate::wolfha::SubjectKind::Vm { // A VM hands off by freeze → final delta → terminate: // 1. QMP `stop` freezes the vCPUs with the process (and its QMP // monitor) still alive — the disk stops changing but a delta // can still be taken through the block layer; // 2. the final incremental therefore captures the EXACT final // state, which is what makes the demoted copy's chain token // trustworthy for later reverse deltas; // 3. SIGTERM ends the process (the native graceful stop — // vms/manager.rs stop_vm — a frozen guest can't answer ACPI, // so "graceful to the guest" stopped being an option at the // freeze; the guest state was already captured in 2). let was_running = { let c = container.clone(); web::block(move || crate::wolfha::subject_is_running(crate::wolfha::SubjectKind::Vm, &c)) .await.unwrap_or(false) }; let mut handoff_token: Option = None; if was_running { let c = container.clone(); let paused = web::block(move || crate::vms::manager::VmManager::new().pause_vm(&c)).await; if let Ok(Err(e)) = &paused { // Not fatal: the takeover proceeds either way, the new // primary just gets the last periodic state. Honest note. final_sync_note = format!(" (could not freeze the VM for a final delta: {})", e); } if final_sync && matches!(paused, Ok(Ok(()))) { let c = container.clone(); match web::block(move || crate::wolfha::vm_take_delta(&c)).await { Ok(Ok((delta_path, _size))) => { let entry_snapshot = crate::wolfha::HaStore::load().get(&container).cloned(); let prev = entry_snapshot.as_ref() .and_then(|e| e.vm_chain.clone()) .unwrap_or_default(); let next = uuid::Uuid::new_v4().to_string(); let secret = crate::auth::load_cluster_secret(); // The promoting node MUST get this delta (it is // about to run the VM); the other standbys get it // too so their chains stay intact — any that miss // it will refuse the new primary's first delta and // be re-seeded automatically, so a failure here // degrades to bandwidth, never to divergence. let st = crate::wolfha::sync_vm_replica( &container, &new_primary, &secret, &delta_path, &prev, &next, ).await; if st.ok { handoff_token = Some(next.clone()); for peer in entry_snapshot.map(|e| e.replicas).unwrap_or_default() { if peer.node_id == new_primary.node_id || peer.address == new_primary.address || crate::wolfha::peer_is_local(&peer) { continue; } let ost = crate::wolfha::sync_vm_replica( &container, &peer, &secret, &delta_path, &prev, &next, ).await; if !ost.ok { tracing::warn!( "wolfha[{}]: handoff delta did not reach standby {} ({}) — it will be re-seeded by the new primary", container, peer.node_id, ost.message); } } } else { final_sync_note = format!( " (final delta failed: {} — the promoted copy has the last periodic sync)", st.message); } let _ = std::fs::remove_file(&delta_path); } Ok(Err(e)) => { final_sync_note = format!( " (final delta could not be taken: {} — the promoted copy has the last periodic sync)", e); } Err(e) => { final_sync_note = format!(" (final delta task failed: {})", e); } } } // Terminate and WAIT for the process to be gone — promotion on // the other node starts a copy with this VM's MAC and IPs, and // two of those alive at once is the split brain HA exists to // prevent. SIGTERM first (clean QEMU shutdown, flushes the // block layer), SIGKILL only if it lingers. let c = container.clone(); let stopped = web::block(move || -> Result<(), String> { let mgr = crate::vms::manager::VmManager::new(); mgr.stop_vm(&c, false)?; for _ in 0..240 { if !mgr.check_running(&c) { return Ok(()); } std::thread::sleep(std::time::Duration::from_millis(500)); } mgr.stop_vm(&c, true)?; for _ in 0..20 { if !mgr.check_running(&c) { return Ok(()); } std::thread::sleep(std::time::Duration::from_millis(500)); } Err("the QEMU process would not exit".to_string()) }).await; match stopped { Ok(Ok(())) => {} Ok(Err(e)) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("could not stop VM '{}' for handoff: {}", container, e) })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } let c = container.clone(); let np = new_primary.clone(); let blk = web::block(move || crate::wolfha::demote_local(&c, np)).await; match blk { Ok(Ok(())) => {} Ok(Err(e)) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } // demote_local cleared the chain token (a demoted VM copy is // normally unprovable). This handoff is the one exception: the // final delta was taken off a frozen disk and confirmed applied, // so this copy IS the token's content — restoring it lets the new // primary send this standby incrementals instead of a full // re-seed. if let Some(next) = handoff_token { let mut store = crate::wolfha::HaStore::load(); if let Some(e) = store.get_mut(&container) { e.vm_chain = Some(next); let _ = store.save(); } } return HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": format!("'{}' stopped and demoted to replica{}", container, final_sync_note), })); } // Stop first so the final delta captures a quiesced rootfs. let c = container.clone(); let stop = web::block(move || { if containers::lxc_is_running(&c) { containers::lxc_stop(&c) } else { Ok(String::new()) } }).await; match stop { Ok(Ok(_)) => {} Ok(Err(e)) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("could not stop '{}' for handoff: {}", container, e) })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } if final_sync { let secret = crate::auth::load_cluster_secret(); // Stopped above, so this snapshot IS the container's final state. let status = if kind == crate::wolfha::SubjectKind::PveContainer { crate::wolfha::pve_final_sync(&container, &new_primary, &secret).await } else { crate::wolfha::sync_one_replica(&container, &new_primary, &secret).await }; if !status.ok { // The handoff still proceeds — the promoting side decided to // take over; it just gets the last periodic state instead of // a perfect final image. Say so. final_sync_note = format!(" (final delta failed: {} — the promoted copy has the last periodic sync)", status.message); } } let c = container.clone(); let blk = web::block(move || crate::wolfha::demote_local(&c, new_primary)).await; match blk { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": format!("'{}' stopped and demoted to replica{}", container, final_sync_note), })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct WolfHaResumeReq { pub container: String, /// The node this copy was demoted in favour of — the one asking. pub from_node: String, /// The replica set this copy had before the handoff. Demotion clears /// it, and without it a resumed primary would sync only to the node /// that asked, silently dropping every other standby. #[serde(default)] pub replicas: Vec, } /// POST /api/wolfha/resume — a node whose promotion FAILED after this /// node had already stopped and demoted itself for the handoff asks it to /// take the container back. Accepted only when this copy is exactly that /// handoff's leftover: a stale replica whose recorded primary is the /// asking node, and stopped. It is then promoted here like any other /// (preflight, start, rollback on failure). pub async fn wolfha_resume( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let from = body.from_node.trim().to_string(); let replicas = body.replicas.clone(); let me = match wolfha_self_peer(&state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let c = container.clone(); let blk = web::block(move || -> Result<(), String> { let store = crate::wolfha::HaStore::load(); let entry = store.get(&c) .ok_or_else(|| format!("'{}' is not WolfHA-managed on this node", c))?; let handed_to = entry.primary.as_ref().map(|p| p.node_id.as_str()).unwrap_or(""); if entry.role != crate::wolfha::HaRole::Replica || !entry.stale || handed_to != from { return Err(format!( "'{}' here is not a copy that was just handed to {} — refusing to start it", c, from)); } if crate::wolfha::subject_is_running(entry.kind, &c) { return Err(format!("'{}' is already running here", c)); } if !replicas.is_empty() { let mut store = crate::wolfha::HaStore::load(); if let Some(e) = store.get_mut(&c) { e.replicas = replicas; store.save()?; } } crate::wolfha::promote_local(&c, Some(me)) }).await; if matches!(blk, Ok(Ok(()))) { // The handed-back set can name one machine under two ids (the // asking node lists itself under its registry alias) — same // canonicalisation a successful promotion does. crate::wolfha::dedupe_replicas(&container, &state.cluster); } match blk { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::Conflict().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/promote — make THIS node's copy the active primary. /// This is both failover (old primary dead — takeover with the last /// synced state) and failback (old primary alive — coordinated handoff: /// it stops, pushes a final quiesced delta here, demotes itself, and /// only then do we start). Invoked via the UI on the node to promote. pub async fn wolfha_promote( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let store = crate::wolfha::HaStore::load(); let Some(entry) = store.get(&container) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("'{}' is not WolfHA-managed on this node", container) })); }; if entry.role == crate::wolfha::HaRole::Primary && !entry.stale { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("'{}' is already the active primary on this node", container) })); } let current_primary = entry.primary.clone(); // The primary's replica set as this standby knows it (it rides along // in every delta's HaMeta) — handed back on a resume. let replica_set = entry.replicas.clone(); let kind = entry.kind; let self_peer = match wolfha_self_peer(&state) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; // Can this node start its copy at all? Checked BEFORE the handoff // asks the primary to stop — on 2026-11-22 gateway's primary was // stopped for a standby that could never have started (a bind-mount // source was missing), turning a refusal into an outage. { let c = container.clone(); match web::block(move || crate::wolfha::binds::preflight_start(kind, &c)).await { Ok(Ok(())) => {} Ok(Err(e)) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Promotion refused — nothing was stopped: {}", e) })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } let tasks = state.migration_tasks.clone(); let task_id = migration_create(&tasks); let tid = task_id.clone(); let secret = state.cluster_secret.clone(); let cluster_for_dedupe = state.cluster.clone(); tokio::spawn(async move { // Coordinated handoff when the current primary answers; plain // takeover when it doesn't (that's the disaster case this // feature exists for). let mut handoff_msg = "current primary unreachable — taking over with the last synced state".to_string(); // Set once the old primary has stopped and demoted itself — from // then on a failed start here must hand the container back. let mut handed_off_by: Option = None; // The address the old primary answered the handoff on. It joins // this container's standbys once promoted, and a standby recorded // under an address that doesn't answer never gets another sync. let mut answered_at: Option<(String, u16)> = None; if let Some(primary) = current_primary { migration_update(&tasks, &tid, "handoff", &format!("Asking {} to stop '{}' and push a final delta…", primary.node_id, container)); let payload = serde_json::json!({ "container": container, "new_primary": self_peer, "final_sync": true, }); let client = &*API_HTTP_CLIENT; // A primary that ANSWERS is alive, whatever it says. Before // this, an error reply ("could not stop it for handoff") was // treated exactly like silence — and silence means "take over", // so a live primary that refused got a second copy started // beside it. let mut refused: Option = None; let mut unreachable: Vec = Vec::new(); 'addresses: for (addr, port) in crate::wolfha::peer_addresses(&cluster_for_dedupe, &primary) { for url in build_node_urls(&addr, port, "/api/wolfha/demote") { match client.post(&url) .peer_auth(secret.clone()) .timeout(std::time::Duration::from_secs(1800)) .json(&payload) .send().await { Ok(r) if r.status().is_success() => { let v = r.json::().await.unwrap_or_default(); handoff_msg = v.get("message").and_then(|m| m.as_str()) .unwrap_or("clean handoff from the old primary").to_string(); handed_off_by = Some(primary.clone()); answered_at = Some((addr.clone(), port)); break 'addresses; } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); let msg = serde_json::from_str::(&body).ok() .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(|s| s.to_string())) .unwrap_or_else(|| body.chars().take(200).collect()); refused = Some(format!("HTTP {}: {}", status, msg)); break 'addresses; } Err(e) => unreachable.push(format!("{} ({})", url, e)), } } } if let Some(why) = refused { migration_fail(&tasks, &tid, &format!( "Promotion stopped — {} answered but refused the handoff ({}). It is still the primary and nothing was started here.", primary.node_id, why)); return; } if handed_off_by.is_none() && let Some(ago) = wolfha_peer_seen_online(&cluster_for_dedupe, &primary.node_id) { migration_fail(&tasks, &tid, &format!( "Promotion stopped — {} did not answer the handoff on any address it is known by ({}), but the cluster heard from it {} s ago. Taking over now could start a second copy of '{}' beside one that is still running. Fix this node's connection to {} (or stop '{}' there), then promote again.", primary.node_id, unreachable.join("; "), ago, container, primary.node_id, container)); return; } } migration_update(&tasks, &tid, "start", &format!("Promoting and starting '{}' here…", container)); let c = container.clone(); let me = self_peer.clone(); let blk = web::block(move || { if let Some((a, p)) = &answered_at { crate::wolfha::set_primary_address(&c, a, *p)?; } crate::wolfha::promote_local(&c, Some(me)) }).await; if matches!(blk, Ok(Ok(()))) { // A replica set inherited through a failover can hold the same // machine under two aliases — canonicalise it immediately. crate::wolfha::dedupe_replicas(&container, &cluster_for_dedupe); } let failure = match blk { Ok(Ok(())) => { migration_done(&tasks, &tid, &format!( "'{}' is now active on this node ({}). Its old node holds a stale copy that catches up on the next sync rounds.", container, handoff_msg)); return; } Ok(Err(e)) => format!("Promotion failed: {}", e), Err(e) => format!("Promotion task failed: {}", e), }; // The old primary already stopped for us. Hand the container back // rather than leave it down — its copy is the exact state it // stopped in (nothing ran anywhere since). let Some(old) = handed_off_by else { migration_fail(&tasks, &tid, &failure); return; }; migration_update(&tasks, &tid, "resume", &format!("{} — asking {} to start '{}' again…", failure, old.node_id, container)); let payload = serde_json::json!({ "container": container, "from_node": self_peer.node_id, "replicas": replica_set, }); let mut resume_err = String::from("no address answered"); let mut resumed = false; let resume_urls: Vec = crate::wolfha::peer_addresses(&cluster_for_dedupe, &old) .into_iter() .flat_map(|(a, p)| build_node_urls(&a, p, "/api/wolfha/resume")) .collect(); for url in resume_urls { match API_HTTP_CLIENT.post(&url) .peer_auth(secret.clone()) .timeout(std::time::Duration::from_secs(300)) .json(&payload) .send().await { Ok(r) if r.status().is_success() => { let _ = r.bytes().await; resumed = true; break; } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); resume_err = serde_json::from_str::(&body).ok() .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(|s| s.to_string())) .unwrap_or_else(|| format!("HTTP {}", status)); } Err(e) => resume_err = e.to_string(), } } if resumed { migration_fail(&tasks, &tid, &format!( "{} '{}' was started again on {}, which is its primary again — nothing is down.", failure, container, old.node_id)); } else { migration_fail(&tasks, &tid, &format!( "{} AND {} could not start '{}' again ({}) — it is DOWN: promote it on {} from its WolfHA page.", failure, old.node_id, container, resume_err, old.node_id)); } }); HttpResponse::Ok().json(serde_json::json!({ "task_id": task_id })) } /// POST /api/wolfha/drop — a primary tells this replica the HA /// relationship ended. Only ever deletes data that carries the replica /// marker. pub async fn wolfha_drop( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = wolfha_peer_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let destroy = body.remove_replicas; let blk = web::block(move || -> Result { let mut store = crate::wolfha::HaStore::load(); // Read the kind BEFORE removing the entry — afterwards there is // nothing left to tell us what this copy was. let kind = store.get(&container).map(|e| e.kind).unwrap_or_default(); let datasets = store.get(&container).map(|e| e.zfs_datasets.clone()).unwrap_or_default(); store.remove(&container); store.save()?; if kind == crate::wolfha::SubjectKind::PveContainer { if destroy { return crate::wolfha::pve_remove_replica(&container, &datasets); } return Ok(format!( "'{}' is no longer WolfHA-managed here; the stopped Proxmox container and its volumes were left in place (onboot stays 0)", container )); } if kind == crate::wolfha::SubjectKind::Vm { // A VM replica is a disk image plus a definition, not a rootfs // directory, so it is removed through the VM store. if destroy { if crate::wolfha::subject_is_running(kind, &container) { return Err(format!("VM replica '{}' is RUNNING here — refusing to delete it", container)); } crate::wolfha::vm_remove_replica(&container)?; return Ok(format!("VM replica '{}' removed", container)); } return Ok(format!( "'{}' is no longer WolfHA-managed here; the dormant VM copy was left in place", container )); } if crate::wolfha::is_replica(&container) { if destroy { if containers::lxc_is_running(&container) { return Err(format!("replica '{}' is RUNNING here — refusing to delete it", container)); } let dir = format!("{}/{}", containers::lxc_base_dir(&container), container); std::fs::remove_dir_all(&dir).map_err(|e| format!("delete replica: {}", e))?; Ok(format!("replica '{}' removed", container)) } else { let _ = std::fs::remove_file(crate::wolfha::marker_path(&container)); Ok(format!("'{}' kept as an ordinary (stopped) container", container)) } } else { Ok("no replica data on this node".to_string()) } }).await; match blk { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/wolfha/disable — stop protecting a container. Runs on the /// primary; notifies every replica to drop (and optionally delete) its /// copy, restores the autostart flag WolfHA took over. pub async fn wolfha_disable( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let container = body.container.trim().to_string(); if !crate::auth::is_safe_name(&container) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let store = crate::wolfha::HaStore::load(); let Some(entry) = store.get(&container).cloned() else { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("'{}' is not WolfHA-managed on this node", container) })); }; let mut notes: Vec = Vec::new(); // Detach the dirty bitmap so we do not leave replication state inside // an image WolfStack no longer manages. Best-effort: a VM that is not // running has no monitor to talk to, and failing the whole disable // because of that would strand the operator. if entry.kind == crate::wolfha::SubjectKind::Vm && entry.role == crate::wolfha::HaRole::Primary { let vm = container.clone(); if let Ok(Err(e)) = web::block(move || crate::wolfha::vm_end_tracking(&vm)).await { notes.push(format!( "The disk's dirty bitmap could not be removed ({}). It is harmless, but \ `qemu-img info` will still list it; remove it with \ `qemu-img bitmap --remove` when the VM is next stopped.", e )); } } if entry.role == crate::wolfha::HaRole::Primary { let client = &*API_HTTP_CLIENT; let secret = state.cluster_secret.clone(); for peer in &entry.replicas { let urls = build_node_urls(&peer.address, peer.port, "/api/wolfha/drop"); let payload = serde_json::json!({ "container": container, "remove_replicas": body.remove_replicas }); let mut ok = false; for url in &urls { match client.post(url) .peer_auth(secret.clone()) .timeout(std::time::Duration::from_secs(60)) .json(&payload) .send().await { Ok(r) if r.status().is_success() => { ok = true; break; } Ok(r) => { let _ = r.bytes().await; } Err(_) => {} } } if !ok { notes.push(format!("replica on {} unreachable — its copy remains until dropped manually", peer.node_id)); } } if entry.kind == crate::wolfha::SubjectKind::PveContainer { // The replication snapshots are bases nobody will send from now. let (c, ds) = (container.clone(), entry.zfs_datasets.clone()); let _ = web::block(move || crate::wolfha::pve_destroy_our_snapshots(&c, &ds)).await; } if entry.autostart_managed { // Hand the boot back to whatever owned it before HA: the LXC // flag for containers, the VM sidecar flag for VMs, `onboot` // for a Proxmox container. if entry.kind == crate::wolfha::SubjectKind::PveContainer { let c = container.clone(); if let Ok(Err(e)) = web::block(move || crate::wolfha::pve_set_onboot(&c, true)).await { notes.push(format!("could not restore the container's onboot flag: {}", e)); } } else if entry.kind == crate::wolfha::SubjectKind::Vm { let c = container.clone(); if let Ok(Err(e)) = web::block(move || crate::wolfha::vm_set_autostart(&c, true)).await { notes.push(format!("could not restore the VM's autostart flag: {}", e)); } } else { let _ = containers::lxc_set_autostart(&container, true); } } } else { // Disabling from a replica just abandons the local copy. let _ = std::fs::remove_file(crate::wolfha::marker_path(&container)); } let mut store = crate::wolfha::HaStore::load(); store.remove(&container); if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let mut message = format!("HA disabled for '{}'", container); if !notes.is_empty() { message.push_str(". "); message.push_str(¬es.join("; ")); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": message })) } /// POST /api/containers/lxc/import-external — import from external cluster /// Auth: X-WolfStack-Secret (same cluster) or X-Transfer-Token (cross-cluster) or session cookie pub async fn lxc_import_external( req: HttpRequest, state: web::Data, mut payload: actix_multipart::Multipart, ) -> HttpResponse { // Accept cluster secret (same cluster), transfer token (cross-cluster), or session auth // validate_inter_node_secret, not `==`: the latter missed the // on-disk secret (rejecting legitimate peers after a rotation) and // compared in non-constant time. let has_secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .map(|v| crate::auth::validate_inter_node_secret_from(v, &state.cluster_secret, peer_ip(&req))) .unwrap_or(false); let has_token = req.headers().get("X-Transfer-Token") .and_then(|v| v.to_str().ok()) .map(validate_transfer_token) .unwrap_or(false); if !has_secret && !has_token && let Err(resp) = require_auth(&req, &state) { return resp; } // Delegate to the standard import logic lxc_import_endpoint_inner(&mut payload).await } /// Shared import logic for both internal and external imports async fn lxc_import_endpoint_inner( payload: &mut actix_multipart::Multipart, ) -> HttpResponse { let import_dir = std::path::Path::new("/tmp/wolfstack-imports"); let _ = std::fs::create_dir_all(import_dir); let mut new_name = String::new(); let mut storage = None; let mut archive_path = None; let mut wolfnet_ip: Option = None; let mut archive_format = String::new(); // "vzdump" or "tar.gz" let mut lxc_config: Option = None; // source config, for a bootable standalone import let mut start_after_import = false; // migrate sets this to boot + verify the destination let mut preserve_identity = false; // migrate (a move) sets this to keep IP/MAC/WolfNet as-is let mut target_bridge: Option = None; // operator-chosen destination bridge for the primary NIC use futures::StreamExt; while let Some(item) = payload.next().await { let mut field = match item { Ok(f) => f, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error": format!("Multipart error: {}", e)})), }; let field_name = field.name().unwrap_or("").to_string(); match field_name.as_str() { "new_name" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } new_name = String::from_utf8_lossy(&buf).trim().to_string(); } "storage" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_string(); if !s.is_empty() { storage = Some(s); } } "wolfnet_ip" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_string(); if !s.is_empty() { wolfnet_ip = Some(s); } } "meta" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_string(); if let Ok(meta) = serde_json::from_str::(&s) { archive_format = meta.get("archive_format").and_then(|v| v.as_str()).unwrap_or("").to_string(); // The source container's LXC config, carried so a // standalone import can write a bootable config. lxc_config = meta.get("lxc_config").and_then(|v| v.as_str()).map(|c| c.to_string()); } } "start" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_ascii_lowercase(); start_after_import = s == "1" || s == "true" || s == "yes"; } "preserve_identity" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_ascii_lowercase(); preserve_identity = s == "1" || s == "true" || s == "yes"; } "target_bridge" => { let mut buf = Vec::new(); while let Some(chunk) = field.next().await { if let Ok(data) = chunk { buf.extend_from_slice(&data); } } let s = String::from_utf8_lossy(&buf).trim().to_string(); if !s.is_empty() { target_bridge = Some(s); } } "archive" => { // Use UUID filename — pick extension based on source archive format let ext = if archive_format == "vzdump" { "tar.zst" } else { "tar.gz" }; let filename = format!("lxc-import-{}.{}", uuid::Uuid::new_v4(), ext); let dest = import_dir.join(&filename); let mut file = match std::fs::File::create(&dest) { Ok(f) => f, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Write error: {}", e)})), }; use std::io::Write; while let Some(chunk) = field.next().await { if let Ok(data) = chunk && let Err(e) = file.write_all(&data) { return HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Write error: {}", e)})); } } archive_path = Some(dest); } _ => { while field.next().await.is_some() {} } } } if new_name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "new_name is required"})); } if !crate::auth::is_safe_name(&new_name) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // An explicitly-requested bridge must exist HERE, on the destination — // pct/lxc both accept any bridge name silently and the container then // just fails to start (or lands nowhere). Refuse up front with the // name so the operator can fix the choice, not debug a dead container. if let Some(ref b) = target_bridge && (!crate::auth::is_safe_name(b) || !std::path::Path::new(&format!("/sys/class/net/{}", b)).exists()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("bridge '{}' does not exist on this destination node", b), })); } let archive = match archive_path { Some(p) => p, None => return HttpResponse::BadRequest().json(serde_json::json!({"error": "archive file is required"})), }; // Import (tar extract, optionally an lxc-start that polls up to ~8s) // is blocking work — run it off the async runtime via web::block so a // multi-GB extract or a slow boot doesn't stall a worker thread. let archive_str = archive.to_string_lossy().to_string(); let nn = new_name.clone(); let storage_c = storage.clone(); let carried = lxc_config.clone(); let pre_ip = wolfnet_ip.clone(); let bridge_c = target_bridge.clone(); let blk = web::block(move || -> Result<(String, Option), String> { let outcome = containers::lxc_import(&archive_str, &nn, storage_c.as_deref(), carried.as_deref(), bridge_c.as_deref())?; let _ = std::fs::remove_file(&archive_str); if preserve_identity { // MOVE: reproduce the container exactly. Only the host rootfs // path changes; MAC, bridge IP and WolfNet IP are kept as the // source had them (the source is stopped, so nothing collides). containers::lxc_migrate_fixup(&nn); if let Some(ip) = pre_ip.as_deref() { containers::lxc_set_wolfnet_marker(&nn, ip); } } else { // CLONE / restore / cross-cluster: the original still exists, so // give this copy a fresh identity to avoid IP/MAC collisions. let wolfnet_marker = format!("{}/{}/.wolfnet", containers::lxc_base_dir(&nn), nn); let _ = std::fs::remove_dir_all(&wolfnet_marker); // Rewrite rootfs.path/hostname/networking for this host. On a // carried config this re-points host-specific keys; on a // synthesised one it finishes off the hwaddr + IPv4. containers::lxc_clone_fixup_ip(&nn); let ip_to_use = pre_ip.or_else(containers::next_available_wolfnet_ip); if let Some(ip) = ip_to_use { let _ = containers::lxc_attach_wolfnet(&nn, &ip); } } // When the caller is a migrate orchestrator it asks us to boot the // destination and confirm it reaches RUNNING (lxc_start polls and // returns the lxc log tail on failure). Otherwise leave it stopped // for the operator to start manually — the historical behaviour. let start_err = if start_after_import { containers::lxc_start(&outcome.start_id).err() } else { None }; Ok((outcome.message, start_err)) }) .await; match blk { Ok(Ok((message, start_err))) => { if start_after_import { if let Some(err) = start_err { // Imported but did not boot — report so a migrate caller // can roll back to the source. The container is left in // place so the operator can inspect the log tail in `err`. return HttpResponse::Ok().json(serde_json::json!({ "message": message, "started": false, "start_error": err, // Report what THIS node actually did with the identity — // an older destination that didn't parse preserve_identity // takes the clone path and this is false, so the migrate // orchestrator must not claim the address was kept from its // own request flag alone. "kept_address": preserve_identity, })); } return HttpResponse::Ok().json(serde_json::json!({ "message": message, "started": true, "kept_address": preserve_identity, })); } HttpResponse::Ok().json(serde_json::json!({"message": message, "kept_address": preserve_identity})) } Ok(Err(e)) => { let _ = std::fs::remove_file(&archive); HttpResponse::InternalServerError().json(serde_json::json!({"error": e})) } Err(e) => { let _ = std::fs::remove_file(&archive); HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("Import task failed: {}", e)})) } } } /// Ask a destination whether an LXC import under `name` would collide /// there (GET /api/containers/lxc/import-name-check). Returns true only /// on a definitive "taken" answer — an unreachable destination or an /// older one without the endpoint returns false, so the import-time /// collision check remains the backstop. `name` has already passed /// is_safe_name, so it needs no URL encoding. async fn remote_lxc_name_taken( urls: &[String], name: &str, secret: Option<&str>, token: Option<&str>, ) -> bool { let client = &*API_HTTP_CLIENT; for url in urls { let mut rb = client .get(format!("{}?name={}", url, name)) .timeout(std::time::Duration::from_secs(10)); if let Some(s) = secret { rb = rb.peer_auth(s); } if let Some(t) = token { rb = rb.header("X-Transfer-Token", t.to_string()); } match rb.send().await { Ok(r) if r.status().is_success() => { return r.json::().await .ok() .and_then(|v| v.get("taken").and_then(|t| t.as_bool())) .unwrap_or(false); } Ok(r) => { let _ = r.bytes().await; } Err(_) => {} } } false } pub type MigrationTasks = Arc>>; /// Helper: update a migration task's stage/message. Resets the /// per-stage progress counters so a stage transition always starts /// with a blank progress bar rather than showing the previous stage's /// percentage. pub fn migration_update(tasks: &MigrationTasks, id: &str, stage: &str, message: &str) { if let Ok(mut map) = tasks.write() && let Some(task) = map.get_mut(id) { task.stage = stage.to_string(); task.message = message.to_string(); task.percent = None; task.bytes_done = None; task.bytes_total = None; } } /// Update the per-stage progress indicators without changing the /// current stage. Pass `percent` alone (a 0.0–100.0 float) when there /// are no byte counts, or pass byte counts and let the helper /// recompute percent. pub fn migration_progress( tasks: &MigrationTasks, id: &str, bytes_done: Option, bytes_total: Option, percent: Option, ) { if let Ok(mut map) = tasks.write() && let Some(task) = map.get_mut(id) { if let Some(b) = bytes_done { task.bytes_done = Some(b); } if let Some(b) = bytes_total { task.bytes_total = Some(b); } if let Some(p) = percent { task.percent = Some(p.clamp(0.0, 100.0)); } else if let (Some(d), Some(t)) = (task.bytes_done, task.bytes_total) && t > 0 { task.percent = Some(((d as f64 / t as f64) * 100.0).clamp(0.0, 100.0)); } } } pub fn migration_fail(tasks: &MigrationTasks, id: &str, error: &str) { if let Ok(mut map) = tasks.write() && let Some(task) = map.get_mut(id) { task.stage = "failed".to_string(); task.message = error.to_string(); task.error = Some(error.to_string()); task.completed = true; } } pub fn migration_done(tasks: &MigrationTasks, id: &str, message: &str) { if let Ok(mut map) = tasks.write() && let Some(task) = map.get_mut(id) { task.stage = "done".to_string(); task.message = message.to_string(); task.completed = true; task.percent = Some(100.0); } } /// Create a new migration task entry and return the generated id. The /// task starts in `preflight` stage — callers transition it via /// `migration_update` as soon as real work begins. pub fn migration_create(tasks: &MigrationTasks) -> String { let id = format!( "mig_{}", &uuid::Uuid::new_v4().to_string().replace('-', "")[..12] ); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); if let Ok(mut map) = tasks.write() { // Evict old finished tasks. The map had no eviction at all, so // every migration/protect/backup task ever started stayed in // memory for the process lifetime. Finished tasks are kept for a // day so the operator can still read the full outcome text // afterwards (RutgerDiehard, 2026-08-08: "where can I find this // full text?"), then the newest MAX_KEPT survive regardless of // age. Unfinished tasks are never evicted — something is still // polling them. const KEEP_FINISHED_SECS: u64 = 24 * 3600; const MAX_KEPT: usize = 200; map.retain(|_, t| !t.completed || now.saturating_sub(t.started_at) < KEEP_FINISHED_SECS); if map.len() > MAX_KEPT { let mut finished: Vec<(String, u64)> = map.iter() .filter(|(_, t)| t.completed) .map(|(k, t)| (k.clone(), t.started_at)) .collect(); finished.sort_by_key(|(_, at)| *at); // oldest first let excess = map.len() - MAX_KEPT; for (k, _) in finished.into_iter().take(excess) { map.remove(&k); } } map.insert(id.clone(), MigrationTask { id: id.clone(), stage: "preflight".to_string(), message: "Preparing…".to_string(), completed: false, error: None, started_at: now, percent: None, bytes_done: None, bytes_total: None, }); } id } /// GET /api/migration/{id}/status — poll migration task progress pub async fn migration_status( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if let Ok(map) = state.migration_tasks.read() && let Some(task) = map.get(&id) { return HttpResponse::Ok().json(task); } HttpResponse::NotFound().json(serde_json::json!({"error": "Task not found"})) } /// GET /api/migration/tasks — recent tasks on this node, newest first, /// with their FULL final message and error text. /// /// Every task's outcome used to be readable only through /// `/api/migration/{id}/status`, which needs an id the operator no /// longer has once the popup is gone — so a migration that succeeded /// "but said it couldn't copy a file" left nowhere to read the detail /// (RutgerDiehard, 2026-08-08). Tasks are kept for 24h (see /// `migration_create`), so this is the record that outlives the toast. pub async fn migration_tasks_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut tasks: Vec = match state.migration_tasks.read() { Ok(map) => map.values().cloned().collect(), Err(_) => Vec::new(), }; tasks.sort_by_key(|task| std::cmp::Reverse(task.started_at)); HttpResponse::Ok().json(serde_json::json!({ "tasks": tasks })) } /// POST /api/containers/lxc/{name}/migrate-external — migrate to external cluster (background task) pub async fn lxc_migrate_external( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); // The URL name doubles as the destination-name fallback and is // interpolated into the preflight check URL — same gate as new_name. if !crate::auth::is_safe_name(&name) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } // An explicit destination name from the caller wins; validate it up // front so a bad name fails before anything is stopped or exported. let requested_name = body.new_name.as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(String::from); if let Some(ref n) = requested_name && !crate::auth::is_safe_name(n) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid container name"})); } let target_url = body.target_url.clone(); let target_token = body.target_token.clone(); let storage_val = body.storage.as_deref().unwrap_or("").to_string(); let ext_target_bridge = body.target_bridge.as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(String::from); let preserve_address = body.preserve_address.unwrap_or(false); let start_after = body.start_after.unwrap_or(false); // The source's WolfNet IP, carried only when the operator asked to keep // the source's identity — mirrors the same-cluster move. let src_wolfnet_ip = if preserve_address { containers::lxc_get_wolfnet_ip(&name) } else { None }; let cluster_secret = state.cluster_secret.clone(); // Attach our cluster secret only when the destination is a member of THIS // cluster. A genuine external cluster authenticates with `target_token` // (federation), never with our fleet-root secret — so gating this way // stops the secret leaking to an arbitrary destination without changing // any working migration path. let attach_secret = target_is_cluster_node(&state, &target_url); let tasks = state.migration_tasks.clone(); // Create task entry let task_id = migration_create(&tasks); migration_update(&tasks, &task_id, "preflight", "Checking destination connectivity..."); let tid = task_id.clone(); // Spawn migration in background tokio::spawn(async move { // 1. Pre-flight let preflight_urls = build_external_urls(&target_url, "/api/storage/list"); let preflight_client = &*API_HTTP_CLIENT; let mut preflight_ok = false; let mut preflight_err = String::new(); for url in &preflight_urls { // Just check connectivity — any HTTP response means the destination is running let mut rb = preflight_client.get(url) .timeout(std::time::Duration::from_secs(10)); if attach_secret { rb = rb.peer_auth(cluster_secret.clone()); } match rb.send().await { Ok(resp) => { let _ = resp.bytes().await; preflight_ok = true; break; } // any response = reachable Err(e) => { preflight_err = format!("{}: {}", url, e); } } } if !preflight_ok { migration_fail(&tasks, &tid, &format!("Cannot reach destination: {}", preflight_err)); return; } // An explicitly-chosen destination name is collision-checked before // anything is stopped or exported — zero downtime on a clash. The // token is only peeked by the check endpoint, never spent. let check_urls = build_external_urls(&target_url, "/api/containers/lxc/import-name-check"); let secret_for_check = attach_secret.then(|| cluster_secret.clone()); if let Some(ref rn) = requested_name && remote_lxc_name_taken(&check_urls, rn, secret_for_check.as_deref(), Some(&target_token)).await { migration_fail(&tasks, &tid, &format!( "'{}' already exists on the destination — nothing was stopped or transferred. Pick a different Destination name in the migrate dialog and run it again.", rn)); return; } // 2. Export migration_update(&tasks, &tid, "export", "Stopping container for export..."); let _ = containers::lxc_stop(&name); let (archive_path, meta) = match containers::lxc_export(&name) { Ok(v) => v, Err(e) => { let _ = containers::lxc_start(&name); migration_fail(&tasks, &tid, &format!("Export failed: {}", e)); return; } }; let _ = containers::lxc_start(&name); migration_update(&tasks, &tid, "export", "Reading archive..."); // Destination name: the caller's explicit choice, else the source's // real hostname from the export metadata. On a Proxmox source `name` // is the bare VMID ("131") — defaulting to it shipped containers that // arrived nameless (jdelrue 2026-08-07, PVE→standalone: "name only // arrived as CT131"). Falls back to `name` when the hostname doesn't // survive is_safe_name (it already passed the source's route match). let new_name = requested_name.clone().unwrap_or_else(|| { if meta.name != name && crate::auth::is_safe_name(&meta.name) { meta.name.clone() } else { name.clone() } }); // The defaulted name is only known post-export — collision-check it // before paying for the upload (the source is already back up). if requested_name.is_none() && remote_lxc_name_taken(&check_urls, &new_name, secret_for_check.as_deref(), Some(&target_token)).await { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); migration_fail(&tasks, &tid, &format!( "'{}' already exists on the destination — nothing was transferred. Set a different Destination name in the migrate dialog and run it again.", new_name)); return; } let archive_bytes = match std::fs::read(&archive_path) { Ok(b) => b, Err(e) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); migration_fail(&tasks, &tid, &format!("Read archive: {}", e)); return; } }; let size_mb = archive_bytes.len() / (1024 * 1024); migration_update(&tasks, &tid, "upload", &format!("Uploading {} MB to destination...", size_mb)); // 3. Upload let import_urls = build_external_urls(&target_url, "/api/containers/lxc/import-external"); let file_name = archive_path.file_name().unwrap_or_default().to_string_lossy().to_string(); let client = &*API_HTTP_CLIENT; let mut last_err: Option = None; for import_url in &import_urls { let mut form = reqwest::multipart::Form::new() .text("new_name", new_name.clone()) .text("storage", storage_val.clone()) .text("meta", serde_json::to_string(&meta).unwrap_or_default()) .part("archive", reqwest::multipart::Part::bytes(archive_bytes.clone()) .file_name(file_name.clone())); if let Some(b) = ext_target_bridge.clone() { form = form.text("target_bridge", b); } // Opt-in: keep the source's IP/MAC, and/or boot on arrival. if preserve_address { form = form.text("preserve_identity", "1"); if let Some(ip) = src_wolfnet_ip.clone() { form = form.text("wolfnet_ip", ip); } } if start_after { form = form.text("start", "1"); } let mut rb = client.post(import_url) .timeout(std::time::Duration::from_secs(600)) .header("X-Transfer-Token", &target_token); if attach_secret { rb = rb.peer_auth(cluster_secret.clone()); } match rb.multipart(form) .send() .await { Ok(r) => { containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); if r.status().is_success() { // The import's message carries the network-fallback // warning (wrong-bridge → vmbr0/lxcbr0) — surface it, // don't drop the body (see lxc_migrate). let body = r.json::().await.unwrap_or_else(|_| serde_json::json!({})); let import_warning = body.get("message").and_then(|v| v.as_str()) .and_then(|m| m.find("WARNING:").map(|i| format!("\n\n{}", &m[i..]))) .unwrap_or_default(); migration_update(&tasks, &tid, "import", "Importing on destination..."); // Report the arrival state honestly: whether it kept // its address, and whether it started (only when the // operator asked it to). // Trust the destination's report of what it actually did, // not our local request flag: an older node that ignores // preserve_identity assigns a fresh address but we still // asked for one. When the field is absent (pre-kept_address // node) we cannot confirm, so we hedge rather than assert. let id_note = match body.get("kept_address").and_then(|v| v.as_bool()) { Some(true) => " It kept its source IP and MAC.", Some(false) => " It was given a fresh IP and MAC — update DNS if needed.", None if preserve_address => " You asked to keep its IP and MAC — an older destination may have assigned a fresh one instead, so check it on the destination and update DNS if needed.", None => " It was given a fresh IP and MAC — update DNS if needed.", }; let start_note = if start_after { match body.get("started").and_then(|v| v.as_bool()) { Some(true) => " Destination is running.".to_string(), _ => { let serr = body.get("start_error").and_then(|v| v.as_str()).unwrap_or("check its log on the destination"); format!(" It was asked to start but did not reach RUNNING ({}).", serr) } } } else { " Destination is stopped — start it manually.".to_string() }; migration_done(&tasks, &tid, &format!( "Container '{}' transferred as '{}'.{}{}{}", name, new_name, start_note, id_note, import_warning)); } else { let err = r.text().await.unwrap_or_default(); migration_fail(&tasks, &tid, &format!("Import failed: {}", err)); } return; } Err(e) => { last_err = Some(e.to_string()); continue; } } } containers::lxc_export_cleanup(archive_path.to_str().unwrap_or("")); migration_fail(&tasks, &tid, &format!("Transfer failed on all ports: {}", last_err.unwrap_or_default())); }); // Return task ID immediately HttpResponse::Ok().json(serde_json::json!({ "task_id": task_id, "message": "Migration started" })) } // ─── Mount / Volume Management Endpoints ─── /// GET /api/containers/docker/{id}/volumes — list Docker container volumes pub async fn docker_volumes( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // web::block: docker_list_volumes shells out to `docker inspect`. Inline in // an async handler it pins a worker, and when the workers are busy the // request simply stalls — the migrate dialog's volume section then never // renders at all, showing neither the copy choice nor an error // (RutgerDiehard, 2026-08-07). match web::block(move || containers::docker_list_volumes(&id)).await { Ok(mounts) => HttpResponse::Ok().json(mounts), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("could not read this container's mounts: {}", e) })), } } #[derive(Deserialize)] pub struct DockerUpdateConfigReq { pub autostart: Option, pub memory_mb: Option, pub cpus: Option, #[serde(default)] pub wolfnet_ip: Option, } pub async fn docker_update_config( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match containers::docker_update_config(&id, body.autostart, body.memory_mb, body.cpus, body.wolfnet_ip.clone()) { Ok(msg) => { // Re-inspect AFTER the update (and after any compose-file // edit + docker-update retry) and return the authoritative // autostart state. Frontend uses this value directly to // set the checkbox — it does NOT trust the user's intent. // That closes the class of bugs where `docker update` // succeeded, the verify passed, but the subsequent list // fetch somehow returned a stale/different value (cache, // combined-inspect parse edge case, multi-writer race, // whatever). The checkbox now renders exactly what // `docker inspect` says right now. let verified_autostart: Option = std::process::Command::new("docker") .args(["inspect", "-f", "{{.HostConfig.RestartPolicy.Name}}", &id]) .output().ok() .and_then(|o| if o.status.success() { Some(String::from_utf8_lossy(&o.stdout).trim().to_string()) } else { None }) .map(|p| !p.is_empty() && p != "no"); HttpResponse::Ok().json(serde_json::json!({ "message": msg, "autostart": verified_autostart, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/docker/{id}/env — update environment variables (recreates container) pub async fn docker_update_env( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let env: Vec = match body.get("env").and_then(|v| v.as_array()) { Some(arr) => arr.iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) .filter(|s| !s.is_empty()) .collect(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'env' array" })), }; match containers::docker_recreate_with_env(&id, &env) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/docker/{id}/raw-config — rebuild the container /// from an edited `docker inspect` JSON. This lets operators add binds, /// change ports, tweak labels, adjust any config field without having /// to `docker rm` and re-run by hand. Recreation is rename-based: the /// old container is kept renamed until the new one is successfully /// created, then removed; on failure we rename back so nothing is /// lost. /// /// The request body is the inspect JSON the UI fetched from /// `GET /inspect`, with the operator's edits applied. We don't diff /// against the current state — we just treat the JSON as the new /// spec. Fields that aren't part of a container spec (State, /// NetworkSettings.IPAddress, Created timestamps, etc.) are ignored, /// so the operator can't break things by leaving those stale. pub async fn docker_update_raw_config( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // Docker's inspect output is always a single-element array. The // UI may send it either way (bare object OR 1-element array), // accommodate both. let spec = match &*body { serde_json::Value::Array(arr) if arr.len() == 1 => arr[0].clone(), serde_json::Value::Object(_) => body.clone(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Body must be a docker-inspect JSON object (or a 1-element array of one)", })), }; let spec_for_task = spec.clone(); let id_for_task = id.clone(); let res = tokio::task::spawn_blocking(move || { containers::docker_recreate_from_inspect(&id_for_task, &spec_for_task) }).await; match res { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("recreate task panicked: {}", e) })), } } /// GET /api/containers/docker/{id}/inspect — inspect raw docker config pub async fn docker_inspect( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match containers::docker_inspect(&id) { Ok(json) => HttpResponse::Ok().json(json), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── LXC disk: inspect / resize / migrate ─────────────────────── #[derive(serde::Deserialize)] pub struct LxcResizeRequest { /// Target absolute size in GB. Backend converts to bytes / Proxmox /// short form. Must be ≥ current usage (refused otherwise). pub size_gb: u64, /// Volume id for Proxmox containers. Defaults to "rootfs" when /// unset. Native LXC always grows the rootfs. #[serde(default)] pub volume: Option, } #[derive(serde::Deserialize)] pub struct LxcMigrateStorageRequest { /// Target storage path (native) or Proxmox storage id (PVE). pub target: String, /// Whether to remove the source after a successful copy. Defaults /// to false — we keep the source until the user confirms the new /// copy boots OK. #[serde(default)] pub remove_source: bool, /// Volume id for Proxmox containers. Defaults to "rootfs". #[serde(default)] pub volume: Option, } /// GET /api/containers/lxc/{name}/disk — current backend, size, used. pub async fn lxc_disk_info( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_storage::inspect(&name) { Ok(info) => HttpResponse::Ok().json(info), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/lxc/{name}/disk/resize — grow the rootfs (or /// a specific Proxmox volume) to a new absolute size in GB. pub async fn lxc_disk_resize( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let r = body.into_inner(); let info = match containers::lxc_storage::inspect(&name) { Ok(i) => i, Err(e) => return HttpResponse::NotFound().json(serde_json::json!({ "error": e })), }; let new_bytes = r.size_gb.saturating_mul(1024 * 1024 * 1024); if info.proxmox { // Route via PVE API. Look up the matching PveClient by node name. let vol = r.volume.unwrap_or_else(|| "rootfs".into()); let pve = match find_pve_client(&state, &info.pve_node).await { Some(c) => c, None => return HttpResponse::ServiceUnavailable().json(serde_json::json!({ "error": "no Proxmox node registered for this container" })), }; let size_str = format!("{}G", r.size_gb); match pve.lxc_resize_disk(info.pve_vmid, &vol, &size_str).await { Ok(upid) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("PVE resize task started: {}", upid), "upid": upid, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } else { match containers::lxc_storage::resize(&name, new_bytes) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } } /// POST /api/containers/lxc/{name}/disk/migrate — move the rootfs to /// a different storage path / pool. pub async fn lxc_disk_migrate( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let r = body.into_inner(); let info = match containers::lxc_storage::inspect(&name) { Ok(i) => i, Err(e) => return HttpResponse::NotFound().json(serde_json::json!({ "error": e })), }; if info.proxmox { let vol = r.volume.unwrap_or_else(|| "rootfs".into()); let pve = match find_pve_client(&state, &info.pve_node).await { Some(c) => c, None => return HttpResponse::ServiceUnavailable().json(serde_json::json!({ "error": "no Proxmox node registered for this container" })), }; match pve.lxc_move_volume(info.pve_vmid, &vol, &r.target, r.remove_source).await { Ok(upid) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("PVE move-volume task started: {}", upid), "upid": upid, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } else { match containers::lxc_storage::migrate(&name, &r.target, r.remove_source) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } } /// Look up a connected PveClient by node id. Returns None if no /// Proxmox node by that id is registered (or if pve_node is empty, /// which means the container is on the local host running pct). async fn find_pve_client( state: &web::Data, pve_node: &str, ) -> Option { if pve_node.is_empty() { return None; } let nodes = state.cluster.get_all_nodes(); let target = nodes.iter().find(|n| n.node_type == "proxmox" && n.id == pve_node)?; let token = target.pve_token.as_deref()?; let node_name = target.pve_node_name.as_deref().unwrap_or(&target.hostname); Some(crate::proxmox::PveClient::new( &target.address, target.port, token, target.pve_fingerprint.as_deref(), node_name, )) } /// GET /api/containers/lxc/{name}/mounts — list LXC container bind mounts pub async fn lxc_mounts( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let mounts = containers::lxc_list_mounts(&name); HttpResponse::Ok().json(mounts) } #[derive(Deserialize)] pub struct AddMountRequest { pub host_path: String, pub container_path: String, #[serde(default)] pub read_only: bool, // PVE-only flags; ignored on native LXC where `lxc.mount.entry` // has no equivalent. #[serde(default)] pub shared: bool, #[serde(default)] pub backup: bool, #[serde(default)] pub quota: bool, #[serde(default)] pub size_gb: Option, } /// POST /api/containers/lxc/{name}/mounts — add bind mount to LXC container pub async fn lxc_add_mount( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); let opts = containers::LxcMountOptions { host_path: body.host_path.clone(), container_path: body.container_path.clone(), read_only: body.read_only, shared: body.shared, backup: body.backup, quota: body.quota, size_gb: body.size_gb, }; match containers::lxc_add_mount(&name, &opts) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct RemoveMountRequest { pub host_path: String, } /// DELETE /api/containers/lxc/{name}/mounts — remove bind mount from LXC container pub async fn lxc_remove_mount( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_remove_mount(&name, &body.host_path) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct LxcSetAutostartReq { pub enabled: bool, } pub async fn lxc_set_autostart( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_set_autostart(&name, body.enabled) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct LxcSetNetworkLinkReq { pub link: String, } pub async fn lxc_set_network_link( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_set_network_link(&name, &body.link) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/containers/lxc/{name}/parsed-config — get structured config pub async fn lxc_parsed_config( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_parse_config(&name) { Some(cfg) => HttpResponse::Ok().json(cfg), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Config not found" })), } } /// POST /api/containers/lxc/{name}/settings — update structured settings pub async fn lxc_update_settings( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let name = path.into_inner(); match containers::lxc_update_settings(&name, &body.into_inner()) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/wolfnet/next-ip — find next available WolfNet IP (cluster-wide) pub async fn wolfnet_next_ip( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Query ALL remote cluster nodes for their used WolfNet IPs // to prevent cross-node IP collisions let nodes = state.cluster.get_all_nodes(); let client = &*API_HTTP_CLIENT; let mut remote_ips: std::collections::HashSet = std::collections::HashSet::new(); for node in &nodes { if node.is_self || !node.online { continue; } let urls = build_node_urls(&node.address, node.port, "/api/wolfnet/used-ips"); for url in &urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(3)) .peer_auth(state.cluster_secret.clone()) .send().await { if let Ok(ips) = resp.json::>().await { for ip in ips { remote_ips.insert(ip); } } break; // Success on this node } } } // Build a combined set of used IPs (local + remote) for allocation // Do NOT inject into WOLFNET_ROUTES cache — that would corrupt routing // with invalid "remote" gateway values let mut all_used: std::collections::HashSet = remote_ips; // Add local used IPs for ip in containers::wolfnet_used_ips() { all_used.insert(ip); } // Add IPs from WOLFNET_ROUTES cache (without modifying it) { let cache = containers::WOLFNET_ROUTES.lock().unwrap(); for ip in cache.keys() { all_used.insert(ip.clone()); } } // Add IPs from routes.json if let Ok(content) = std::fs::read_to_string("/var/run/wolfnet/routes.json") && let Ok(routes) = serde_json::from_str::>(&content) { for ip in routes.keys() { all_used.insert(ip.clone()); } } // Find next available IP that isn't in the combined used set let prefix = containers::wolfnet_subnet_prefix().unwrap_or_default(); if prefix.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "ip": null, "error": "WolfNet is not configured" })); } // Remember every currently-used IP in the ever-used history so a later // release doesn't make the address look brand new. containers::record_wolfnet_ips_used(&all_used.iter().cloned().collect::>()); let history = containers::load_wolfnet_ip_history(); // Prefer a PRISTINE address (free AND never used). Only recycle a // previously-used-but-released IP when no fresh one remains — and flag it // so the UI warns the operator before they reuse it (klasSponsor 2026-06-24: // a recycled IP black-holed because the old node's routing was stale). let mut fresh: Option = None; let mut recycled: Option = None; for i in 2..=254u8 { let ip = format!("{}.{}", prefix, i); if all_used.contains(&ip) { continue; } if !history.contains(&ip) { fresh = Some(ip); break; } if recycled.is_none() { recycled = Some(ip); } } let (picked, previously_used) = match fresh { Some(ip) => (Some(ip), false), None => (recycled, true), }; match picked { // We deliberately do NOT record the suggestion in history — only // genuinely in-use IPs (recorded above from all_used) count, so an // unacted suggestion never pollutes the history with a false // "previously used" flag. Some(ip) => HttpResponse::Ok().json(serde_json::json!({ "ip": ip, "previously_used": previously_used })), None => HttpResponse::Ok().json(serde_json::json!({ "ip": null, "error": "No available IPs in the WolfNet subnet" })), } } /// GET /api/wolfnet/ip-status?ip=X — is this WolfNet IP previously used (and is /// it active on a workload right now)? Drives the reuse warning when an operator /// types/keeps a WolfNet IP manually. pub async fn wolfnet_ip_status( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let ip = query.get("ip").cloned().unwrap_or_default(); let ip = ip.split('/').next().unwrap_or(&ip).trim().to_string(); if ip.parse::().is_err() { return HttpResponse::Ok().json(serde_json::json!({ "previously_used": false, "active_holder": null })); } let ip_for_block = ip.clone(); let previously_used = web::block(move || containers::wolfnet_ip_previously_used(&ip_for_block)) .await.unwrap_or(false); // If something currently holds it, that's the strongest "don't reuse" signal. let active_holder = wolfnet_ip_active_elsewhere(&state, &ip).await; HttpResponse::Ok().json(serde_json::json!({ "previously_used": previously_used, "active_holder": active_holder, })) } /// GET /api/network/conflicts — detect duplicate MACs/IPs across LXC containers pub async fn network_conflicts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let conflicts = containers::detect_network_conflicts(); HttpResponse::Ok().json(conflicts) } /// GET /api/notify/rules — the notification rule set for this node. pub async fn notify_rules_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::notify::NotifyRules::load()) } /// PUT /api/notify/rules — replace the rule set. /// /// Whole-set replacement rather than per-rule CRUD: the file is the unit that /// replicates (last-write-wins on `version`), so a partial update would race /// itself across nodes. pub async fn notify_rules_put( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let rules = body.into_inner(); // Reject a rule that could never fire — a silently-dead rule is the worst // outcome for a notification system. for r in &rules.rules { if r.id.trim().is_empty() || r.name.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "every rule needs an id and a name" })); } } match rules.save() { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "count": rules.rules.len() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/notify/targets — what a probe can be pointed at. /// /// Exists because typing globs is not a usable way to choose 3 containers out /// of several hundred. Returns this node's objects grouped by kind, plus the /// cluster's node list so the editor can offer node/fleet targeting. /// /// Remote nodes are NOT enumerated here: fanning out to every peer to build a /// picker would make opening the editor as slow as the slowest node in the /// fleet. The UI fetches a remote node's objects through the existing node /// proxy only when one is selected. pub async fn notify_targets(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Listing shells out; keep it off the async workers. let objects = web::block(|| { let mut out: Vec = Vec::new(); for c in containers::docker_list_all_cached() { out.push(serde_json::json!({ "backend": "docker", "name": c.name, "state": c.state })); } for c in containers::lxc_list_all_cached() { out.push(serde_json::json!({ "backend": "lxc", "name": c.name, "state": c.state })); } for (name, st) in crate::notify::source_poll::snapshot_libvirt() { out.push(serde_json::json!({ "backend": "libvirt", "name": name, "state": st })); } for (name, st) in crate::notify::source_poll::snapshot_pve() { out.push(serde_json::json!({ "backend": "pve", "name": name, "state": st })); } out }).await; // NOT unwrap_or_default. web::block turns a panic in any of those listers // into an Err, and defaulting it to an empty Vec answered 200 OK with // "objects": [] — so a node full of containers reported itself as empty and // the probe tree faithfully displayed that. A failure to list is an error; // saying so lets the UI show a reason instead of a blank list. let objects = match objects { Ok(v) => v, Err(e) => { tracing::warn!("notify targets: listing failed: {}", e); return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("could not list containers or VMs on this node: {}", e) })); } }; let nodes: Vec = { let n = state.cluster.nodes_read(); n.values() .map(|node| serde_json::json!({ "id": node.id, "name": node.hostname })) .collect() }; HttpResponse::Ok().json(serde_json::json!({ "self_node": crate::notify::local_node_name(), "nodes": nodes, "objects": objects, })) } /// POST /api/notify/test — push a synthetic event through the live rule set. /// /// The only honest way to answer "will this rule actually page me?" without /// waiting for a real outage. pub async fn notify_test( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let object = body.get("object").and_then(|v| v.as_str()).unwrap_or("test-container"); let kind: crate::notify::EventKind = body.get("kind") .and_then(|v| serde_json::from_value(v.clone()).ok()) .unwrap_or(crate::notify::EventKind::ObjectFailed); let node = body.get("node").and_then(|v| v.as_str()).unwrap_or("this-node"); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let event = crate::notify::NotifyEvent { kind, node: node.to_string(), backend: "docker".into(), object: object.to_string(), labels: Default::default(), exit_code: Some(1), restart_count: None, timestamp: now, message: "synthetic test event from the WolfNotify test button".into(), }; // Report which rules matched BEFORE delivering, so a test that matches // nothing is obvious rather than looking like a delivery failure. let rules = crate::notify::NotifyRules::load(); let empty = std::collections::HashMap::new(); let matched: Vec = crate::notify::evaluate(&event, &rules.rules, &empty) .iter().map(|r| r.name.clone()).collect(); let mut cooldowns = std::collections::HashMap::new(); crate::notify::handle_event(event, &mut cooldowns).await; HttpResponse::Ok().json(serde_json::json!({ "matched_rules": matched, "delivered": !matched.is_empty(), })) } /// POST /api/containers/docker/import-spec — receive the runtime configuration /// of a container that is about to be migrated here. /// /// Arrives just before the image. Staged to disk and consumed by the import, /// so the destination can recreate ports, networks and mounts instead of /// creating a bare container. pub async fn docker_import_spec( req: HttpRequest, state: web::Data, body: web::Json, query: web::Query>, ) -> HttpResponse { if require_cluster_auth(&req, &state).is_err() && let Err(resp) = require_auth(&req, &state) { return resp; } let name = match query.get("name") { Some(n) if crate::auth::is_safe_name(n) => n.clone(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid or missing container name" })), }; let path = containers::staged_spec_path(&name); match std::fs::write(&path, body.to_string()) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to stage runtime spec: {}", e) })), } } /// POST /api/containers/docker/import-volume — receive a named volume's /// contents for a container being migrated here. pub async fn docker_import_volume( req: HttpRequest, state: web::Data, mut payload: web::Payload, query: web::Query>, ) -> HttpResponse { if require_cluster_auth(&req, &state).is_err() && let Err(resp) = require_auth(&req, &state) { return resp; } // Two restore modes: a named volume (by name) or a bind mount (by absolute // path). The bind path is validated again in docker_restore_bind — this is // a sending node's input, so it is checked at both ends. let bind_path = query.get("kind").map(|k| k == "bind").unwrap_or(false) .then(|| query.get("path").cloned()) .flatten(); let volume = match (&bind_path, query.get("volume")) { (Some(_), _) => String::new(), (None, Some(v)) if crate::auth::is_safe_name(v) => v.clone(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid or missing volume name (or kind=bind without path)" })), }; // Streamed to disk for the same reason as the image: volume data is the // largest part of most migrations and must never sit in RAM. let staging = crate::paths::transfer_staging_dir(); let tag: String = bind_path.as_deref().unwrap_or(&volume).chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) .collect(); let tar_path = format!("{}/wolfstack-volin-{}.tar", staging, tag); use futures::StreamExt; use tokio::io::AsyncWriteExt; let mut file = match tokio::fs::File::create(&tar_path).await { Ok(f) => f, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to open volume file: {}", e) })), }; while let Some(chunk) = payload.next().await { let chunk = match chunk { Ok(c) => c, Err(e) => { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Volume transfer interrupted: {}", e) })); } }; if let Err(e) = file.write_all(&chunk).await { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write volume file: {}", e) })); } } if let Err(e) = file.flush().await { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to flush volume file: {}", e) })); } drop(file); // Blocking: `docker volume create` plus a tar extraction of the whole // volume. Same reasoning as docker_migrate — off the worker. let bp = bind_path.clone(); let vol = volume.clone(); let tp = tar_path.clone(); let result = web::block(move || match &bp { Some(path) => containers::docker_restore_bind(path, &tp), None => containers::docker_restore_volume(&vol, &tp), }).await.unwrap_or_else(|e| Err(format!("restore task failed: {}", e))); let _ = tokio::fs::remove_file(&tar_path).await; match result { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/containers/docker/import — receive a migrated container image /// Auth: X-WolfStack-Secret (same cluster) or X-Transfer-Token (cross-cluster) or session cookie pub async fn docker_import( req: HttpRequest, state: web::Data, // web::Payload, not web::Bytes: Bytes materialises the ENTIRE image in RAM // before the handler runs, and is capped by the 2 GB PayloadConfig — so a // container larger than that could never be received at all, however much // memory the node had. Streamed to disk instead, there is no ceiling beyond // free disk on the staging volume. mut payload: web::Payload, query: web::Query>, ) -> HttpResponse { let has_secret = require_cluster_auth(&req, &state).is_ok(); let has_token = req.headers().get("X-Transfer-Token") .and_then(|v| v.to_str().ok()) .map(validate_transfer_token) .unwrap_or(false); if !has_secret && !has_token && let Err(resp) = require_auth(&req, &state) { return resp; } let container_name = query.get("name") .cloned() .unwrap_or_else(|| format!("migrated-{}", chrono::Utc::now().timestamp())); // Sanitize container name to prevent path traversal if !crate::auth::is_safe_name(&container_name) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid container name" })); } // Stream the body straight to disk. NOT /tmp — that is tmpfs on stock // Debian 13 and most systemd distros, so the image would land in RAM on the // receiving node exactly as it did on the sender. let staging = crate::paths::transfer_staging_dir(); let tar_path = format!("{}/wolfstack-import-{}.tar", staging, container_name); use futures::StreamExt; use tokio::io::AsyncWriteExt; let mut file = match tokio::fs::File::create(&tar_path).await { Ok(f) => f, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to open import file: {}", e) })), }; while let Some(chunk) = payload.next().await { let chunk = match chunk { Ok(c) => c, Err(e) => { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Transfer interrupted: {}", e) })); } }; if let Err(e) = file.write_all(&chunk).await { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write import file: {}", e) })); } } // Flush before docker reads it — a buffered tail would make `docker load` // fail on a truncated archive. if let Err(e) = file.flush().await { let _ = tokio::fs::remove_file(&tar_path).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to flush import file: {}", e) })); } drop(file); // `docker load` of a multi-GB image, then docker create — blocking, and // long. The sender is waiting on this response, so pinning a worker here // stalls the very transfer that is being completed. let tp = tar_path.clone(); let cn = container_name.clone(); let result = web::block(move || containers::docker_import_image(&tp, &cn)) .await.unwrap_or_else(|e| Err(format!("import task failed: {}", e))); // The staged tar is large and no longer needed either way — leaving it // would fill the staging volume one migration at a time. let _ = tokio::fs::remove_file(&tar_path).await; match result { Ok(msg) => { // Imported container is left stopped — user starts it manually when ready HttpResponse::Ok().json(serde_json::json!({ "message": msg })) }, Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct InstallRuntimeRequest { pub runtime: String, // docker or lxc } /// POST /api/containers/install — install Docker or LXC pub async fn install_container_runtime( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let result = match body.runtime.as_str() { "docker" => containers::install_docker(), "lxc" => containers::install_lxc(), _ => Err(format!("Unknown runtime: {}", body.runtime)), }; match result { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct InstallComponentInContainerRequest { pub runtime: String, // docker or lxc pub container: String, // container name pub component: String, // wolfnet, wolfproxy, etc. } /// POST /api/containers/install-component — install a Wolf component inside a container async fn install_component_in_container( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let runtime = body.runtime.clone(); let container = body.container.clone(); let component = body.component.clone(); // Run in blocking thread since it may take a while let result = web::block(move || { containers::install_component_in_container(&runtime, &container, &component) }).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } /// GET /api/containers/component-version?runtime=lxc&target=name&component=wolfdisk async fn container_component_version( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let runtime = query.get("runtime").cloned().unwrap_or_default(); let target = query.get("target").cloned().unwrap_or_default(); let component = query.get("component").cloned().unwrap_or_default(); if runtime.is_empty() || target.is_empty() || component.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "runtime, target, and component are required"})); } // `component` is interpolated into a shell command (` --version`) // run inside the container, and `target` is the container name — both must // be safe tokens so a query param can't inject a command. `component` is a // binary name (e.g. "wolfdisk"); container names are DNS-safe. if !crate::auth::is_safe_name(&component) || !crate::auth::is_safe_name(&target) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "invalid component or target name"})); } let exec_target = match runtime.as_str() { "docker" => crate::configurator::ExecTarget::Docker(target), "lxc" => crate::configurator::ExecTarget::Lxc(target), _ => return HttpResponse::BadRequest().json(serde_json::json!({"error": "runtime must be docker or lxc"})), }; let cmd = format!("{} --version 2>/dev/null | head -1", component); let result = web::block(move || exec_target.exec(&cmd)).await; match result { Ok(Ok(output)) => { let version = output.split_whitespace() .find(|w| w.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false)) .unwrap_or("") .to_string(); HttpResponse::Ok().json(serde_json::json!({"version": version})) } _ => HttpResponse::Ok().json(serde_json::json!({"version": serde_json::Value::Null})), } } /// GET /api/containers/running — list all running containers for component install UI async fn list_running_containers( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let containers = containers::list_running_containers(); let list: Vec = containers.into_iter().map(|(runtime, name, image)| { serde_json::json!({ "runtime": runtime, "name": name, "image": image }) }).collect(); HttpResponse::Ok().json(list) } // ─── AI Agent API ─── /// GET /api/ai/config — get AI configuration (keys masked) pub async fn ai_get_config( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.ai_agent.config.lock().unwrap(); HttpResponse::Ok().json(config.masked()) } /// POST /api/ai/config — save AI configuration pub async fn ai_save_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config_json; let email_changed; { let mut config = state.ai_agent.config.lock().unwrap(); let email_before = config.email_transport(); // Update fields — only update keys if not masked values if let Some(v) = body.get("agent_enabled").and_then(|v| v.as_bool()) { config.agent_enabled = v; } if let Some(v) = body.get("provider").and_then(|v| v.as_str()) { config.provider = v.to_string(); } if let Some(v) = body.get("cloudflare_account_id").and_then(|v| v.as_str()) { config.cloudflare_account_id = v.trim().to_string(); } if let Some(v) = body.get("cloudflare_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.cloudflare_api_key = v.to_string(); } if let Some(v) = body.get("claude_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.claude_api_key = v.to_string(); } if let Some(v) = body.get("gemini_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.gemini_api_key = v.to_string(); } if let Some(v) = body.get("openrouter_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.openrouter_api_key = v.to_string(); } if let Some(v) = body.get("openai_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.openai_api_key = v.to_string(); } if let Some(v) = body.get("local_url").and_then(|v| v.as_str()) { config.local_url = v.to_string(); } if let Some(v) = body.get("local_api_key").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.local_api_key = v.to_string(); } if let Some(v) = body.get("model").and_then(|v| v.as_str()) { config.model = v.to_string(); } if let Some(v) = body.get("email_enabled").and_then(|v| v.as_bool()) { config.email_enabled = v; } if let Some(v) = body.get("email_to").and_then(|v| v.as_str()) { config.email_to = v.to_string(); } if let Some(v) = body.get("smtp_host").and_then(|v| v.as_str()) { config.smtp_host = v.to_string(); } if let Some(v) = body.get("smtp_port").and_then(|v| v.as_u64()) { config.smtp_port = v as u16; } if let Some(v) = body.get("smtp_from").and_then(|v| v.as_str()) { config.smtp_from = v.to_string(); } if let Some(v) = body.get("smtp_user").and_then(|v| v.as_str()) { config.smtp_user = v.to_string(); } if let Some(v) = body.get("smtp_pass").and_then(|v| v.as_str()) && !v.contains("••••") && !v.is_empty() { config.smtp_pass = v.to_string(); } if let Some(v) = body.get("smtp_tls").and_then(|v| v.as_str()) { config.smtp_tls = v.to_string(); } if let Some(v) = body.get("check_interval_minutes").and_then(|v| v.as_u64()) { config.check_interval_minutes = v as u32; } if let Some(v) = body.get("scan_schedule").and_then(|v| v.as_str()) { config.scan_schedule = v.to_string(); } if let Some(arr) = body.get("accepted_risks").and_then(|v| v.as_array()) { config.accepted_risks = arr.iter() .filter_map(|v| v.as_str().map(|s| s.trim().to_string())) .filter(|s| !s.is_empty() && s.len() <= 200) .collect(); } if let Some(v) = body.get("agent_max_tool_calls").and_then(|v| v.as_u64()) { // Range-clamp on save so the on-disk file always holds a // sane value — defence-in-depth alongside the use-time // clamp in `effective_agent_max_tool_calls`. config.agent_max_tool_calls = (v as u32).clamp(1, 100); } if let Some(v) = body.get("agent_tool_call_limit_enabled").and_then(|v| v.as_bool()) { config.agent_tool_call_limit_enabled = v; } // Validate provider and model compatibility if let Err(e) = config.validate() { return HttpResponse::BadRequest().json(serde_json::json!({"error": e})); } if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } email_changed = config.email_transport() != email_before; // Serialize full config (with real keys) for cluster sync config_json = serde_json::to_value(&*config).unwrap_or_default(); } // Alert email is part of the shared alert settings: a change here makes // this node's copy the newest, so the reconcile can't push an older // email setup back over it. if email_changed { alert_settings_changed(&state); } // Push to same-cluster peers and report what actually happened. The // results ride back on the save response so a peer that rejected or was // unreachable is visible immediately, rather than surfacing days later as // "the mail relay on node 3 uses the wrong SMTP host". let peers = ai_propagate_config_to_peers(&state, &config_json, 5).await; let failed: Vec<&AiConfigPeerResult> = peers.iter().filter(|p| !p.ok).collect(); HttpResponse::Ok().json(serde_json::json!({ "status": "saved", "peers": peers, "peers_failed": failed.len(), })) } #[derive(serde::Serialize)] struct AiConfigPeerResult { hostname: String, address: String, ok: bool, #[serde(skip_serializing_if = "Option::is_none")] error: Option, } /// Push the AI/email config to every online peer in THIS node's cluster. /// /// Cluster-scoped deliberately: this payload carries the SMTP password and /// every AI provider key, so a multi-cluster bastion must not hand them to a /// different operator's fleet. /// /// `timeout_secs` is short on the save path (the operator is waiting on a form /// submit) and longer for the explicit push (they pressed a button meaning /// "reach them", and a slow-but-alive peer is worth waiting for). async fn ai_propagate_config_to_peers( state: &web::Data, config_json: &serde_json::Value, timeout_secs: u64, ) -> Vec { let nodes = state.cluster.get_all_nodes(); let self_cluster = nodes.iter().find(|n| n.is_self) .and_then(|n| n.cluster_name.clone()); let peers: Vec<(String, String, u16)> = nodes.iter() .filter(|n| !n.is_self && n.online && n.node_type == "wolfstack" && crate::agent::same_display_cluster( n.cluster_name.as_deref(), self_cluster.as_deref())) .map(|n| (n.hostname.clone(), n.address.clone(), n.port)) .collect(); if peers.is_empty() { return Vec::new(); } let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let mut futures = Vec::with_capacity(peers.len()); for (hostname, address, port) in peers { let secret = secret.clone(); let client = client.clone(); let payload = config_json.clone(); futures.push(async move { let urls = build_node_urls(&address, port, "/api/ai/config/sync"); for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(timeout_secs)) .peer_auth(&secret) .json(&payload) .send() .await { Ok(resp) if resp.status().is_success() => { let _ = resp.bytes().await; tracing::info!("ai_config: settings propagated to peer '{}' ({})", hostname, address); return AiConfigPeerResult { hostname, address, ok: true, error: None }; } Ok(resp) => { // Reachable peer gave a definitive (non-2xx) answer — // don't retry the other URL candidates for this peer. let status = resp.status(); let body = resp.text().await.unwrap_or_default(); let snippet: String = body.chars().take(200).collect(); tracing::warn!("ai_config: peer '{}' ({}) rejected settings: HTTP {}", hostname, address, status); return AiConfigPeerResult { hostname, address, ok: false, error: Some(format!("HTTP {}: {}", status, snippet)), }; } Err(_) => continue, // connection failed — try next candidate URL } } tracing::warn!("ai_config: could not reach peer '{}' ({}) to propagate settings", hostname, address); AiConfigPeerResult { hostname, address, ok: false, error: Some("unreachable on all known addresses".to_string()), } }); } futures::future::join_all(futures).await } /// POST /api/ai/config/propagate — force-push this node's saved AI/email /// settings to every online peer in the cluster. /// /// The save-time push only reaches nodes that were online at that moment, so a /// node that joined later — or was down for the save — keeps loading defaults /// forever. That is what makes the host mail relay come up pointing at the /// placeholder SMTP host. This is the operator's manual reconcile. pub async fn ai_config_propagate(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } if !crate::ai::config_saved_on_this_node() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "This node has no saved email/AI settings to push. Configure them here first, \ or run this from the node where they were configured." })); } let config_json = { let config = state.ai_agent.config.lock().unwrap(); serde_json::to_value(&*config).unwrap_or_default() }; let peers = ai_propagate_config_to_peers(&state, &config_json, 15).await; let failed = peers.iter().filter(|p| !p.ok).count(); HttpResponse::Ok().json(serde_json::json!({ "pushed": peers.len(), "failed": failed, "peers": peers, })) } /// POST /api/ai/config/sync — receive AI config from another cluster node pub async fn ai_sync_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let new_config = body.into_inner(); if let Err(e) = new_config.save() { warn!("Failed to save synced AI config: {}", e); return HttpResponse::InternalServerError().json(serde_json::json!({"error": e})); } // Update in-memory config let mut config = state.ai_agent.config.lock().unwrap(); *config = new_config; HttpResponse::Ok().json(serde_json::json!({"status": "synced"})) } /// POST /api/ai/test-email — send a test email to verify SMTP settings pub async fn ai_test_email( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.ai_agent.config.lock().unwrap().clone(); if !config.email_enabled || config.email_to.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Email alerts not enabled or no recipient configured" })); } let hostname = hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_else(|_| "unknown".to_string()); let version = env!("CARGO_PKG_VERSION"); let subject = format!("[WolfStack] Test Email from {}", hostname); let body = format!( "✅ WolfStack Test Email\n\n\ This is a test email from your WolfStack AI Agent.\n\n\ Hostname: {}\n\ Version: {}\n\ Time: {}\n\n\ If you received this, your email alert settings are working correctly.", hostname, version, chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC") ); match crate::ai::send_alert_email(&config, &subject, &body) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "status": "sent", "message": format!("Test email sent to {}", config.email_to) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to send: {}", e) })), } } /// POST /api/ai/test-connection — lightweight reachability probe for /// the configured AI provider. Sends a tiny chat completion (no tools, /// max_tokens=8, "ping") with a 15s outer timeout and 5s connect /// timeout. Returns timing breakdown + structured error so the /// "Test Connection" UI can show what actually failed. /// /// Distinct from /api/ai/chat — that path loads the full system /// prompt and 8 tool schemas (~13 KB request body), which is enough /// to trip path-MTU black holes on misconfigured LANs. KO4BSR's /// reproduction. The test endpoint sends ~150 bytes so the URL/auth /// path is exercised without the body-size dependency. pub async fn ai_test_connection( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.ai_agent.config.lock().unwrap().clone(); if !config.is_configured() { return HttpResponse::BadRequest().json(serde_json::json!({ "ok": false, "stage": "config", "error": "AI not configured — set provider/key in Settings → AI Agent", })); } let provider = config.provider.clone(); let url_for_log = match provider.as_str() { "local" => config.local_url.clone(), "openai" => "https://api.openai.com/v1".to_string(), "openrouter" => "https://openrouter.ai/api/v1".to_string(), "cloudflare" => crate::ai::cloudflare_base_url(&config.cloudflare_account_id), "gemini" => format!("https://generativelanguage.googleapis.com/.../{}:generateContent", config.model), // claude-cli shells out to the local `claude` binary — no HTTP, no key. "claude-cli" => "local `claude` CLI (Pro/Max login — no API key)".to_string(), _ => "https://api.anthropic.com/v1/messages".to_string(), }; let started = std::time::Instant::now(); // Reuse simple_chat — it picks the right provider call. The system // prompt and history we pass are intentionally minimal so the // request body stays small (~150 bytes for local, similar for // hosted providers). let result = tokio::time::timeout( std::time::Duration::from_secs(15), crate::ai::simple_chat(&config, "You are a connectivity test. Reply with the single word: OK", &[], "ping"), ).await; let elapsed_ms = started.elapsed().as_millis(); match result { Ok(Ok(reply)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "provider": provider, "url": url_for_log, "model": config.model, "elapsed_ms": elapsed_ms, "reply": reply.chars().take(200).collect::(), })), Ok(Err(e)) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "stage": "request", "provider": provider, "url": url_for_log, "model": config.model, "elapsed_ms": elapsed_ms, "error": e, })), Err(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "stage": "timeout", "provider": provider, "url": url_for_log, "model": config.model, "elapsed_ms": elapsed_ms, "error": format!( "Test request did not complete within 15 seconds. \ The host may be unreachable, blocked by a firewall, or behind a path-MTU black hole. \ Try `curl -v {}` from this machine to diagnose.", url_for_log ), })), } } /// GET /api/ai/suppress?p=&t= — one-click suppress /// from an alert email. Session-free: the HMAC token is the auth. /// Adds the phrase to accepted_risks and returns a minimal HTML page /// confirming what was suppressed. #[derive(Deserialize)] pub struct AiSuppressQuery { pub p: String, pub t: String, } pub async fn ai_suppress_link( state: web::Data, query: web::Query, ) -> HttpResponse { let phrase = query.p.trim().to_string(); if phrase.is_empty() || phrase.len() > 200 { return HttpResponse::BadRequest().body("Invalid phrase"); } if !crate::ai::verify_suppress_token(&phrase, &query.t) { return HttpResponse::Forbidden().body( "Invalid or expired suppress token. \ This link can only be used with a valid HMAC from an alert email sent by this node." ); } // Add to accepted_risks if not already there. let added = { let mut config = state.ai_agent.config.lock().unwrap(); if config.accepted_risks.iter().any(|r| r.eq_ignore_ascii_case(&phrase)) { false } else { config.accepted_risks.push(phrase.clone()); if let Err(e) = config.save() { warn!("Failed to save accepted_risks: {}", e); } true } }; // Minimal inline HTML — no frontend dependency. Explicitly does // NOT include operator session tokens or return to the dashboard // by default; a user who clicked a stale link from a shared inbox // should just see a confirmation, nothing privileged. let escaped: String = phrase.chars() .map(|c| match c { '<' => "<".to_string(), '>' => ">".to_string(), '&' => "&".to_string(), '"' => """.to_string(), _ => c.to_string(), }) .collect(); let body = format!( "Alert suppressed\ \

{}

\

The AI agent will no longer flag this condition in future health checks on this node:

\

{}

\

You can review or remove suppressed items under AI settings → Accepted risks in the WolfStack dashboard.

\ ", if added { "✓ Alert suppressed" } else { "Already suppressed" }, escaped, ); HttpResponse::Ok().content_type("text/html; charset=utf-8").body(body) } /// GET /api/ai/accepted-risks — list suppressed phrases pub async fn ai_accepted_risks_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let risks = state.ai_agent.config.lock().unwrap().accepted_risks.clone(); HttpResponse::Ok().json(serde_json::json!({ "accepted_risks": risks })) } /// POST /api/ai/accepted-risks — replace the list wholesale #[derive(Deserialize)] pub struct AiAcceptedRisksSave { pub accepted_risks: Vec, } pub async fn ai_accepted_risks_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cleaned: Vec = body.accepted_risks.iter() .map(|r| r.trim().to_string()) .filter(|r| !r.is_empty() && r.len() <= 200) .collect(); { let mut config = state.ai_agent.config.lock().unwrap(); config.accepted_risks = cleaned.clone(); if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } } HttpResponse::Ok().json(serde_json::json!({ "accepted_risks": cleaned })) } /// POST /api/ai/accepted-risks/remove — remove one entry by value #[derive(Deserialize)] pub struct AiAcceptedRisksRemove { pub phrase: String, } pub async fn ai_accepted_risks_remove( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let phrase = body.phrase.trim(); let removed; { let mut config = state.ai_agent.config.lock().unwrap(); let before = config.accepted_risks.len(); config.accepted_risks.retain(|r| !r.eq_ignore_ascii_case(phrase)); removed = before - config.accepted_risks.len(); if removed > 0 && let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } } HttpResponse::Ok().json(serde_json::json!({ "removed": removed, "accepted_risks": state.ai_agent.config.lock().unwrap().accepted_risks.clone(), })) } /// POST /api/ai/chat — send a message to the AI agent #[derive(Deserialize)] pub struct AiChatRequest { pub message: String, /// The node ID the user is currently viewing (null/empty = datacenter level) #[serde(default)] pub node_id: Option, /// The page/view the user is currently on (e.g. "dashboard", "containers", "vms", "networking") #[serde(default)] pub view: Option, /// Friendly name of what the user is looking at (e.g. node hostname, container name) #[serde(default)] pub context_name: Option, } pub async fn ai_chat( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; // Build server context for the AI let server_context = { let hostname = hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_else(|_| "unknown".to_string()); // Get local container/VM lists once (reuse for counts and names) let local_docker_list = crate::containers::docker_list_all(); let local_lxc_list = crate::containers::lxc_list_all(); let local_vm_list = state.vms.lock().unwrap().list_vms(); let docker_count = local_docker_list.len(); let lxc_count = local_lxc_list.len(); let vm_count = local_vm_list.len(); let components = crate::installer::get_all_status(); let local_docker: Vec = local_docker_list.iter().map(|c| format!("{} [{}]", c.name, c.state)).collect(); let local_lxc: Vec = local_lxc_list.iter().map(|c| format!("{} [{}]", c.name, c.state)).collect(); let local_vms: Vec = local_vm_list.iter().map(|v| format!("{} [{}]", v.name, if v.running { "running" } else { "stopped" })).collect(); let nodes = state.cluster.get_all_nodes(); // All nodes (including Proxmox nodes that have WolfStack agents) let all_online: Vec<&crate::agent::Node> = nodes.iter().filter(|n| n.online).collect(); // PVE nodes for separate cluster grouping display let pve_nodes: Vec<&crate::agent::Node> = nodes.iter().filter(|n| n.node_type == "proxmox").collect(); let node_info = all_online.iter().map(|n| { let mut line = format!(" - {} ({}) [{}]", n.hostname, n.address, if n.online { "online" } else { "offline" }); if n.docker_count > 0 { line.push_str(&format!(" — {} Docker", n.docker_count)); } if n.lxc_count > 0 { line.push_str(&format!(", {} LXC", n.lxc_count)); } if n.vm_count > 0 { line.push_str(&format!(", {} VMs", n.vm_count)); } // For the local node, include actual names if n.is_self { if !local_docker.is_empty() { line.push_str(&format!("\n Docker: {}", local_docker.join(", "))); } if !local_lxc.is_empty() { line.push_str(&format!("\n LXC: {}", local_lxc.join(", "))); } if !local_vms.is_empty() { line.push_str(&format!("\n VMs: {}", local_vms.join(", "))); } } line }).collect::>().join("\n"); // Group PVE nodes by cluster let mut pve_clusters: std::collections::HashMap> = std::collections::HashMap::new(); for n in &pve_nodes { let key = n.pve_cluster_name.clone() .or_else(|| n.cluster_name.clone()) .unwrap_or_else(|| n.address.clone()); pve_clusters.entry(key).or_default().push(n); } let pve_info = if pve_clusters.is_empty() { "None".to_string() } else { pve_clusters.iter().map(|(cluster_name, cnodes)| { let node_details = cnodes.iter().map(|n| { let metrics_str = if let Some(ref m) = n.metrics { let mem_used_gb = m.memory_used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); let mem_total_gb = m.memory_total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); let root_disk = m.disks.iter().find(|d| d.mount_point == "/").or_else(|| m.disks.first()); let disk_info = root_disk.map(|d| { let used_gb = d.used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); let total_gb = d.total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); format!(", disk {:.1}/{:.1}GB", used_gb, total_gb) }).unwrap_or_default(); format!(" — CPU {:.0}%, RAM {:.1}/{:.1}GB{}", m.cpu_usage_percent, mem_used_gb, mem_total_gb, disk_info) } else { String::new() }; format!(" - {} (pve_node: {}, {}) [{}] — {} VMs, {} CTs{}", n.hostname, n.pve_node_name.as_deref().unwrap_or("?"), n.address, if n.online { "online" } else { "offline" }, n.vm_count, n.lxc_count, metrics_str) }).collect::>().join("\n"); format!(" Cluster '{}' ({} nodes):\n{}", cluster_name, cnodes.len(), node_details) }).collect::>().join("\n") }; // Build user navigation context let user_context = { let mut ctx = String::new(); if let Some(ref nid) = body.node_id { if !nid.is_empty() { let target_node = nodes.iter().find(|n| n.id == *nid); if let Some(tn) = target_node { ctx.push_str(&format!("\n\nUSER IS CURRENTLY VIEWING: Node '{}' ({})", tn.hostname, tn.address)); if tn.node_type == "proxmox" { ctx.push_str(" [Proxmox VE node]"); } } else { ctx.push_str(&format!("\n\nUSER IS CURRENTLY VIEWING: Node ID '{}'", nid)); } } else { ctx.push_str("\n\nUSER IS CURRENTLY VIEWING: Datacenter overview (all nodes)"); } } else { ctx.push_str("\n\nUSER IS CURRENTLY VIEWING: Datacenter overview (all nodes)"); } if let Some(ref view) = body.view && !view.is_empty() { ctx.push_str(&format!(", Page: {}", view)); } if let Some(ref name) = body.context_name && !name.is_empty() { ctx.push_str(&format!(", Context: {}", name)); } // Enumerate containers/VMs on the viewed node (reuse already-fetched local data) if body.node_id.as_ref().map(|s| !s.is_empty()).unwrap_or(false) { let is_self_node = nodes.iter().any(|n| n.is_self && Some(&n.id) == body.node_id.as_ref()); if is_self_node { if !local_docker.is_empty() { ctx.push_str("\n\nDocker containers on this node:"); for name in &local_docker { ctx.push_str(&format!("\n - {}", name)); } } if !local_lxc.is_empty() { ctx.push_str("\n\nLXC containers on this node:"); for name in &local_lxc { ctx.push_str(&format!("\n - {}", name)); } } if !local_vms.is_empty() { ctx.push_str("\n\nVMs on this node:"); for name in &local_vms { ctx.push_str(&format!("\n - {}", name)); } } } else { ctx.push_str("\n\n(Container/VM list for remote nodes is provided by the frontend target picker)"); } } ctx.push_str("\n\nWhen the user says 'this server', 'this node', 'here', etc. they mean the node/view shown above."); ctx.push_str("\nThe user may be asking about a specific container, VM, or the host itself. If it's ambiguous, ask which one they mean."); ctx.push_str("\nWhen proposing [ACTION] fixes, set target=\"local\" for commands on the host node. The user will choose the actual target (host, container, or VM) before approving."); ctx }; format!( "Hostname: {}\nLocal Docker containers: {}\nLocal LXC containers: {}\nLocal VMs: {}\n\ Components: {}\n\nAll Nodes ({}):\n{}\n\nProxmox Clusters:\n{}{}", hostname, docker_count, lxc_count, vm_count, components.iter().map(|c| format!("{:?}: {}", c.component, if c.running { "running" } else { "stopped" })).collect::>().join(", "), all_online.len(), node_info, pve_info, user_context, ) }; // Build cluster node list for remote command execution. // Include ALL online nodes (including Proxmox nodes that have WolfStack agents). // URLs come from build_node_urls so the AI agent inherits the same // HTTPS-first chain federation uses; v23.12 dropped the implicit // http://addr:port+1 attempt that this code used pre-migration. let cluster_nodes: Vec<(String, String, Vec)> = { let nodes = state.cluster.get_all_nodes(); nodes.iter() .filter(|n| !n.is_self && n.online) .map(|n| { // The AI agent appends "/api/ai/exec" etc to the base URL, // so we strip the path component: build_node_urls with an // empty path returns scheme://host:port URLs. let urls = build_node_urls(&n.address, n.port, ""); (n.id.clone(), n.hostname.clone(), urls) }) .collect() }; // The agent's chat() call is the slow path: on a local model (LM Studio, // Ollama, llama.cpp) it sends the full tools schema + cluster context and // can generate up to 4096 tokens over several round-trips — *minutes* in // the wild. Holding one HTTP request open that long is fragile: a reverse // proxy that buffers the response (Cloudflare, and any nginx/Caddy/Traefik // not explicitly told to stream) sits on every byte until the handler // finishes, then either delivers it all at once or — as a tester hit — resets // the connection with "Error in input stream". An earlier SSE-heartbeat // attempt (v25.1.22) failed for exactly this reason: a buffering proxy // swallows the heartbeats, so they never reach the browser (observed TTFB // of 5.5 min while the model generated). // // Robust fix that needs NO cooperation from the proxy: don't hold a long // request at all. POST starts the work in a background task and returns a // job id immediately (sub-second — nothing buffers a tiny response). The // browser then polls GET /api/ai/chat/result with sub-second requests until // the job is done. Short requests sail through any proxy untouched. prune_ai_chat_jobs(); let job_id = format!("aichat-{}", uuid::Uuid::new_v4().simple()); { let mut jobs = AI_CHAT_JOBS.lock().unwrap(); jobs.insert(job_id.clone(), AiChatJob { created_at: chrono::Utc::now().timestamp(), owner: username.clone(), status: AiChatJobStatus::Running, response: None, actions: None, error: None, }); } let agent = state.ai_agent.clone(); let cluster_secret = state.cluster_secret.clone(); let message = body.message.clone(); let job_id_task = job_id.clone(); tokio::spawn(async move { let result = agent.chat(&message, &server_context, &cluster_nodes, &cluster_secret).await; let mut jobs = AI_CHAT_JOBS.lock().unwrap(); // The job may have been pruned (>10 min) or evicted; only update if it's // still present. Never holds the lock across an await — chat() already // finished above. if let Some(job) = jobs.get_mut(&job_id_task) { match result { Ok((response, actions)) => { let actions_json: Vec = actions.iter().map(|a| { serde_json::json!({ "id": a.id, "title": a.title, "command": a.command, "risk": a.risk, "explanation": a.explanation, "target": a.node_target, }) }).collect(); job.response = Some(response); job.actions = Some(actions_json); job.status = AiChatJobStatus::Done; } Err(e) => { job.error = Some(e); job.status = AiChatJobStatus::Error; } } } }); HttpResponse::Ok().json(serde_json::json!({ "job_id": job_id })) } /// In-memory store for async AI chat jobs. The chat agentic loop can run for /// minutes on a slow local model, so POST /api/ai/chat kicks the work onto a /// background task and the browser polls GET /api/ai/chat/result for the /// outcome — see `ai_chat` for why a single long request is unreliable behind a /// buffering proxy. Ephemeral runtime state (never serialised), so a static map /// is the right home; entries are pruned after 20 minutes (see /// `prune_ai_chat_jobs` for why that outlasts the worst-case run). #[derive(Clone, Copy)] enum AiChatJobStatus { Running, Done, Error } struct AiChatJob { created_at: i64, /// The authenticated identity that created the job (the `require_auth` /// username, or "cluster-node" for proxied inter-node requests). The result /// poll checks this so one operator can't read another's chat by guessing / /// lifting a job id from logs — OWASP A01. UUID v4 ids already make ids /// unguessable; this is defence in depth. owner: String, status: AiChatJobStatus, response: Option, actions: Option>, error: Option, } static AI_CHAT_JOBS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); /// Drop chat jobs older than 20 minutes so the map can't grow unbounded. The /// retention window must outlast the worst-case task lifetime — the agentic /// loop runs up to 3 rounds (src/ai/mod.rs chat()), each capped at the 300s /// per-request timeout = 900s — plus the frontend's 16-minute poll budget, so a /// genuinely slow run still has its result waiting when the browser collects /// it. 1200s clears that with margin. fn prune_ai_chat_jobs() { let cutoff = chrono::Utc::now().timestamp() - 1200; let mut jobs = AI_CHAT_JOBS.lock().unwrap(); jobs.retain(|_, j| j.created_at >= cutoff); } /// GET /api/ai/chat/result?id= — poll for an async chat result. /// Returns `{status:"running"}` while the agent works, `{status:"done", /// response, actions}` on success, `{status:"error", error}` on failure, or /// `{status:"unknown"}` if the job id isn't found (expired/never existed). pub async fn ai_chat_result( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let job_id = match query.get("id") { Some(id) => id.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing id parameter" })), }; let jobs = AI_CHAT_JOBS.lock().unwrap(); // Scope to the creator: a job belonging to someone else is reported exactly // like a non-existent one ("unknown"), never distinguished — so a lifted id // leaks neither the response nor the job's existence. match jobs.get(&job_id).filter(|job| job.owner == username) { Some(job) => match job.status { AiChatJobStatus::Running => HttpResponse::Ok().json(serde_json::json!({ "status": "running" })), AiChatJobStatus::Done => HttpResponse::Ok().json(serde_json::json!({ "status": "done", "response": job.response.clone().unwrap_or_default(), "actions": job.actions.clone().unwrap_or_default(), })), AiChatJobStatus::Error => HttpResponse::Ok().json(serde_json::json!({ "status": "error", "error": job.error.clone().unwrap_or_else(|| "AI request failed".to_string()), })), }, None => HttpResponse::Ok().json(serde_json::json!({ "status": "unknown" })), } } /// POST /api/ai/action — approve or reject a proposed action. /// Approve only marks the action as "approved" — it does NOT execute it. /// The terminal (console.html) fetches the command via GET /api/ai/action/command /// and sends it to the PTY shell, so the user sees it run live. #[derive(Deserialize)] pub struct AiActionRequest { pub action_id: String, #[serde(default = "default_true")] pub approved: bool, } fn default_true() -> bool { true } pub async fn ai_action( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; if !body.approved { match state.ai_agent.reject_action(&body.action_id, &username) { Ok(()) => return HttpResponse::Ok().json(serde_json::json!({ "status": "rejected" })), Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // Mark as approved (terminal will fetch and execute the command) { let mut pa = state.ai_agent.pending_actions.lock().unwrap(); let now = chrono::Utc::now().timestamp(); if let Some(a) = pa.iter_mut().find(|a| a.id == body.action_id) { if a.status != "pending" { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Action already {}", a.status) })); } if now - a.created_at > 600 { a.status = "expired".to_string(); return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Action expired" })); } a.status = "approved".to_string(); a.approved_by = username.clone(); crate::ai::log_action_audit(a, "approved", &username, ""); return HttpResponse::Ok().json(serde_json::json!({ "status": "approved", "command": a.command, })); } } HttpResponse::NotFound().json(serde_json::json!({ "error": "Action not found" })) } /// GET /api/ai/action/command?id=xxx — retrieve the command for an approved action (one-time, for terminal auto-exec) pub async fn ai_action_command( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let action_id = match query.get("id") { Some(id) => id.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({"error": "Missing id parameter"})), }; let pa = state.ai_agent.pending_actions.lock().unwrap(); // Only return command for approved actions (approved by the POST /api/ai/action call) match pa.iter().find(|a| a.id == action_id && a.status == "approved") { Some(a) => HttpResponse::Ok().json(serde_json::json!({ "command": a.command, "title": a.title, })), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Action not found, not approved, or expired" })), } } /// POST /api/ai/action/exec — execute an approved action command on a remote node (cluster proxy) pub async fn ai_action_exec( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // This runs `bash -c` on the host, so it is a shell sink and takes the // shell gate: a bare cluster secret is refused, the built-in default is // refused outright, and a peer must carry the operator attribution // (`X-WolfStack-Proxied` + `X-WolfStack-Actor`) that the approving // node's `ai::approve_action` now stamps. Pre-fix this accepted any valid // cluster secret — the `/api/ai/action/exec` row of the 2026-08-29 // report by @baeseungwon1010 (incomplete fix for GHSA-r3mw-2wmq-j6jg). if let Err(resp) = require_operator_auth(&req, &state) { return resp; } match crate::ai::execute_action_command(&body.command) { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "output": output })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e })), } } /// POST /api/ai/exec — execute a safe read-only command (used by cluster proxy) #[derive(Deserialize)] pub struct AiExecRequest { pub command: String, } pub async fn ai_exec( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::ai::execute_safe_command(&body.command) { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "output": output, "exit_code": 0, })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e, })), } } /// GET /api/ai/status — agent status and last health check /// GET /api/system-check — runs the dependency audit on this node /// and returns a structured report for the Settings UI. pub async fn system_check_run( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let ai_enabled = state.ai_agent.config.lock().unwrap().is_configured(); // Run both audits off the async executor — they shell out to lsmod, // systemctl, docker info, ss, journalctl, pgrep etc. and we don't // want actix's async runtime parked on them. Run them in parallel // so the user-visible latency matches the slower of the two, not // the sum. let deps_fut = web::block(crate::systemcheck::run_checks); let sec_fut = web::block(crate::security::run_security_checks); let (deps_res, sec_res) = tokio::join!(deps_fut, sec_fut); let mut checks = match deps_res { Ok(v) => v, Err(e) => return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("System check failed: {}", e) })), }; // Cluster-scoped checks (cross-node WolfNet IP conflicts) need // AppState for the cached remote topologies. Runs synchronously // here — cheap because it just reads in-memory topology snapshots. let mut cluster_checks = crate::security::run_cluster_checks(&state); checks.append(&mut cluster_checks); match sec_res { Ok(mut v) => checks.append(&mut v), Err(e) => { // Security scan error doesn't fail the whole endpoint — // surface it as a single Warning entry so the user sees // why the Security category looks thin. Any other outcome // would hide a real issue. checks.push(crate::systemcheck::DependencyCheck { name: "Security scan errored".into(), category: "Security".into(), status: crate::systemcheck::DepStatus::Warning, version: None, detail: format!("Security scan task failed: {}. Non-fatal — dependency checks above are still accurate.", e), install_hint: None, ai_helpful: false, install_package: None, }); } } HttpResponse::Ok().json(serde_json::json!({ "checks": checks, "ai_enabled": ai_enabled, "hostname": hostname::get().ok().and_then(|h| h.into_string().ok()), })) } /// GET /api/security/secret-audit — lightweight read-only audit of /// committed-default secrets on this node. Used by: /// • the dashboard banner (asks once per page load, decides colour) /// • Settings → Security (renders the full finding list + remediation) /// • Stage 4 telemetry — the count is folded into the heartbeat /// /// Returns the same `secret_audit::Finding` shape the scanner uses; /// the structured JSON lets the frontend present per-finding migration /// buttons without re-parsing scanner text. pub async fn secret_audit_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let findings = crate::secret_audit::audit(); let high_or_above = findings.iter() .filter(|f| !matches!(f.severity, crate::secret_audit::Severity::Info)) .count(); HttpResponse::Ok().json(serde_json::json!({ "findings": findings, "finding_count": high_or_above, "using_default_cluster_secret": crate::secret_audit::is_using_default_cluster_secret(), })) } /// POST /api/system-check/ask-ai — given a specific failing dependency, /// ask the AI agent for tailored remediation advice. Body: `{ name, detail, install_hint }`. #[derive(serde::Deserialize)] pub struct SystemCheckAskAi { pub name: String, pub detail: String, pub install_hint: Option, } pub async fn system_check_ask_ai( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } if !state.ai_agent.config.lock().unwrap().is_configured() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "AI agent is not configured — enable it in Settings → AI Agent first" })); } // Include a few lines of host context so the AI gives distro- // specific advice. detect_distro() returns an enum with no Display // impl so format with {:?}. let distro = format!("{:?}", crate::installer::detect_distro()); let os_release = std::fs::read_to_string("/etc/os-release") .unwrap_or_default() .lines() .filter(|l| l.starts_with("PRETTY_NAME=") || l.starts_with("ID=")) .collect::>() .join(" | "); let prompt = format!( "WolfStack system check found a problem with `{}`.\n\ Detail: {}\n\ Suggested fix already shown to admin: {}\n\ Host: {} ({})\n\ Architecture: {}\n\n\ Give concrete remediation steps the admin can run *right now*. \ If the dependency simply isn't supported on this OS/arch, say so clearly \ and suggest the closest workaround. Keep it short and distro-aware.", body.name, body.detail, body.install_hint.clone().unwrap_or_else(|| "(none)".into()), os_release, distro, std::env::consts::ARCH, ); match state.ai_agent.analyze_issue(&prompt).await { Some(advice) => HttpResponse::Ok().json(serde_json::json!({ "advice": advice })), None => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "AI agent did not respond — check provider API key and model in Settings" })), } } pub async fn ai_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.ai_agent.config.lock().unwrap(); let last_check = state.ai_agent.last_health_check.lock().unwrap().clone(); let alert_count = state.ai_agent.alerts.lock().unwrap().len(); let history_count = state.ai_agent.chat_history.lock().unwrap().len(); let pending_actions: Vec = { let pa = state.ai_agent.pending_actions.lock().unwrap(); let now = chrono::Utc::now().timestamp(); pa.iter() .filter(|a| a.status == "pending" && (now - a.created_at) < 600) .map(|a| serde_json::json!({ "id": a.id, "title": a.title, "command": a.command, "risk": a.risk, "explanation": a.explanation, "target": a.node_target, "created_at": a.created_at, })) .collect() }; HttpResponse::Ok().json(serde_json::json!({ "configured": config.is_configured(), "provider": config.provider, "model": config.model, "last_health_check": last_check, "alert_count": alert_count, "chat_message_count": history_count, "knowledge_base_size": state.ai_agent.knowledge_base.len(), "pending_actions": pending_actions, })) } /// GET /api/ai/alerts — historical alerts pub async fn ai_alerts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let alerts = state.ai_agent.alerts.lock().unwrap().clone(); HttpResponse::Ok().json(alerts) } /// GET /api/ai/diagnostics — read-only operator view of the local agent. pub async fn ai_diagnostics( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let metrics_state = state.clone(); let resource = tokio::task::spawn_blocking(move || { let metrics = metrics_state.monitor.lock().unwrap().collect(); let (gpu, active_compute_processes) = crate::monitoring::collect_gpu_metrics(); (metrics, gpu, active_compute_processes) }).await; let (metrics, gpu, active_compute_processes) = match resource { Ok(resource) => resource, Err(_) => return HttpResponse::InternalServerError().json(serde_json::json!({"error": "Resource telemetry unavailable"})), }; let config = state.ai_agent.config.lock().unwrap().masked(); let history_count = state.ai_agent.chat_history.lock().unwrap().len(); let alert_count = state.ai_agent.alerts.lock().unwrap().len(); let request_counts = { let actions = state.ai_agent.pending_actions.lock().unwrap(); let pending = actions.iter().filter(|a| a.status == "pending").count(); serde_json::json!({"total": actions.len(), "pending": pending}) }; HttpResponse::Ok().json(serde_json::json!({ "config": config, "activity": {"history_messages": history_count, "alerts": alert_count, "requests": request_counts}, "metrics": metrics, "gpu": gpu, "active_compute_processes": active_compute_processes, })) } /// GET /api/ai/models?provider=claude|gemini — list available models pub async fn ai_models( req: HttpRequest, state: web::Data, query: web::Query>, body: web::Bytes, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.ai_agent.config.lock().unwrap().clone(); // Optional POST body: lets the UI pass the selected provider plus a // typed-but-not-yet-saved API key so the model dropdown can populate BEFORE // the first Save. Without this it's a chicken-and-egg — saving requires a // model already chosen, but the model list needs the saved key (the operator // could only escape via "Custom…"). The key travels in the body, not the // query string (which lands in access logs) nor a custom header (which the // node proxy strips when this is fetched against a remote node). let body_json: serde_json::Value = if body.is_empty() { serde_json::Value::Null } else { serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null) }; // Reject a masked placeholder (••••…, as returned by GET /api/ai/config) so a // mask never reaches the provider as a real key — fall back to the saved key. let unsaved_key = body_json.get("api_key").and_then(|v| v.as_str()) .map(|s| s.trim()) .filter(|s| !s.is_empty() && !s.contains('\u{2022}')); let provider = query.get("provider").map(|s| s.as_str()) .or_else(|| body_json.get("provider").and_then(|v| v.as_str())) .unwrap_or(&config.provider) .to_string(); // Cloudflare Workers AI exposes ~100 models across multiple modalities // (chat / embeddings / vision / image / TTS). The `/v1/models` listing // is enormous and includes models that aren't chat-completion-compatible, // so we return a short curated list of well-known chat models and let // the operator type any other model name they want — Workers AI also // adds new models faster than we can keep a list up to date. if provider == "cloudflare" { return HttpResponse::Ok().json(serde_json::json!({ "models": [ "@cf/meta/llama-3.1-8b-instruct", "@cf/meta/llama-3.1-70b-instruct", "@cf/meta/llama-3.2-3b-instruct", "@cf/mistralai/mistral-small-3.1-24b-instruct", "@cf/qwen/qwen1.5-14b-chat-awq", "@cf/google/gemma-7b-it", ], "note": "Cloudflare Workers AI offers many more models — pick 'Custom…' to type a model ID (e.g. @cf/meta/llama-3.3-70b-instruct-fp8-fast). See https://developers.cloudflare.com/workers-ai/models/" })); } // Local AI: fetch models from the local server's /v1/models endpoint if provider == "local" { if config.local_url.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "models": ["llama3", "mistral", "codellama", "phi3", "gemma2", "qwen2"], "note": "Enter your local AI URL and save to auto-detect models" })); } let base = config.local_url.trim_end_matches('/'); let url = if base.ends_with("/v1") { format!("{}/models", base) } else { format!("{}/v1/models", base) }; let client = &*API_HTTP_CLIENT; let mut req_builder = client.get(&url).timeout(std::time::Duration::from_secs(5)); if !config.local_api_key.is_empty() { req_builder = req_builder.header("Authorization", format!("Bearer {}", config.local_api_key)); } match req_builder.send().await { Ok(resp) if resp.status().is_success() => { if let Ok(data) = resp.json::().await { let models: Vec = data["data"].as_array() .or_else(|| data["models"].as_array()) .map(|arr| arr.iter().filter_map(|m| m["id"].as_str().or_else(|| m["name"].as_str()).or_else(|| m.as_str()).map(|s| s.to_string())).collect()) .unwrap_or_default(); if !models.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "models": models })); } } HttpResponse::Ok().json(serde_json::json!({ "models": ["llama3", "mistral", "codellama"], "note": "Could not parse model list — showing defaults" })) } Ok(resp) => { let status = resp.status(); let _ = resp.bytes().await; HttpResponse::Ok().json(serde_json::json!({ "models": ["llama3", "mistral"], "error": format!("Server returned {}", status) })) } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "models": ["llama3", "mistral"], "error": format!("Cannot reach {}: {}", url, e) })), } } else if provider == "claude-cli" { // Claude Code CLI has no API key (it uses the local subscription login) // — return its curated static model list directly. match state.ai_agent.list_models(&provider, "").await { Ok(models) => HttpResponse::Ok().json(serde_json::json!({ "models": models })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "models": [], "error": e })), } } else { let saved_key = match provider.as_str() { "gemini" => &config.gemini_api_key, "openrouter" => &config.openrouter_api_key, "openai" => &config.openai_api_key, _ => &config.claude_api_key, }; // Prefer a key the operator just typed (POST body) over the saved one so // the dropdown loads before the config is persisted. let api_key = unsaved_key.unwrap_or(saved_key.as_str()); if api_key.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "models": [], "error": "No API key configured for this provider" })); } match state.ai_agent.list_models(&provider, api_key).await { Ok(models) => HttpResponse::Ok().json(serde_json::json!({ "models": models })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "models": [], "error": e })), } } } // ─── Networking API ─── /// GET /api/networking/interfaces — list all network interfaces pub async fn net_list_interfaces(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(networking::list_interfaces()) } /// GET /api/browse/roots — the directories the operator may browse (the /// mounted shares + local ISO/VM stores). Read-only; auth-gated. pub async fn browse_roots(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let roots = web::block(crate::browse::allowed_roots).await; match roots { Ok(r) => HttpResponse::Ok().json(r), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(serde::Deserialize)] pub struct BrowseQuery { pub path: String } /// GET /api/browse?path= — list one directory. Path-jailed to the /// allowed roots (canonicalized; rejects `..` and symlink escapes). /// Returns metadata only — never file contents. Read-only; auth-gated. pub async fn browse_dir(req: HttpRequest, state: web::Data, q: web::Query) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let path = q.into_inner().path; match web::block(move || crate::browse::list_dir(&path)).await { Ok(Ok(listing)) => HttpResponse::Ok().json(listing), Ok(Err(msg)) => HttpResponse::Forbidden().json(serde_json::json!({ "error": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/network-map — this node's OBSERVED network view for the /// read-only cluster Network Map. Returns the passive topology (bridges, /// interfaces, VLANs, VMs + containers with their IPs and attachments, /// discovered gateways) plus the node's WolfNet overlay IP and the set /// of container names WolfStack itself manages (so the UI can mark /// managed-vs-foreign). The frontend fans this out to every node in a /// cluster (directly for self, via the node proxy for peers) and draws /// the cluster-wide picture. /// /// STRICTLY READ-ONLY: builds via `compute_local_passive` (no zone /// persistence) and `wolfnet_status` (a passive `ip addr` read). It /// discovers, it never changes anything — the promise the map is built /// on for beginner homelabbers. pub async fn network_map(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = state.router.config.read().unwrap().clone(); let self_id = crate::agent::self_node_id(); let node_name = hostname::get() .ok() .and_then(|h| h.into_string().ok()) .unwrap_or_else(|| self_id.clone()); // Subprocess-heavy passive reads (ip/docker/lxc enumeration, // gateway discovery, wolfnet interface read) go on the blocking pool. let self_id_for_block = self_id.clone(); let blocking = web::block(move || { let topo = crate::networking::router::topology::compute_local_passive( &self_id_for_block, &node_name, &cfg, ); let wn = crate::containers::wolfnet_status(&[]); (topo, wn) }).await; let (topo, wn) = match blocking { Ok(v) => v, Err(e) => return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("network-map build failed: {}", e) })), }; // Managed-vs-foreign: a container is WolfStack-managed iff the // WolfRun store has a service instance for its name. In-memory // lookup, no subprocess — safe outside the blocking pool. let managed_names: Vec = topo.containers.iter() .filter(|c| !state.wolfrun.services_managing(&c.name).is_empty()) .map(|c| c.name.clone()) .collect(); let wolfnet_ip = if wn.available && !wn.ip.is_empty() { Some(wn.ip) } else { None }; HttpResponse::Ok().json(serde_json::json!({ "node_id": self_id, "topology": topo, "managed_names": managed_names, "wolfnet_ip": wolfnet_ip, })) } /// GET /api/networking/dns — get DNS configuration pub async fn net_get_dns(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(networking::get_dns()) } /// GET /api/networking/bridges — list bridges (classified LAN/NAT/empty) /// plus candidate physical NICs that could be enslaved into a new LAN /// bridge. Drives the "Create LAN bridge" UI. pub async fn net_list_bridges(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let bridges = web::block(crate::networking::lan_bridge::classify_bridges).await; let nics = web::block(crate::networking::lan_bridge::candidate_nics).await; match (bridges, nics) { (Ok(bridges), Ok(nics)) => HttpResponse::Ok().json(serde_json::json!({ "bridges": bridges, "nics": nics, })), _ => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": "failed to enumerate bridges/NICs" })), } } #[derive(Deserialize)] pub struct LanBridgeCreateRequest { pub bridge_name: String, pub nic: String, #[serde(default)] pub accept_risk: bool, } /// POST /api/networking/lan-bridge — create a LAN bridge enslaving a /// physical NIC. The blocking `ip`/`nmcli` work runs on the actix /// blocking pool. When the chosen NIC is the management NIC, the /// response carries a `pending_confirm` token that must be POSTed back /// (see `net_lan_bridge_confirm`) within `rollback_seconds` or the /// change auto-reverts. pub async fn net_lan_bridge_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let params = crate::networking::lan_bridge::CreateLanBridgeParams { bridge_name: body.bridge_name, nic: body.nic, accept_risk: body.accept_risk, }; match web::block(move || crate::networking::lan_bridge::create_lan_bridge(¶ms)).await { Ok(Ok(outcome)) => HttpResponse::Ok().json(serde_json::json!({ "message": outcome.message, "pending_confirm": outcome.pending_confirm, "rollback_seconds": outcome.rollback_seconds, })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("lan-bridge task: {}", e) })), } } #[derive(Deserialize)] pub struct LanBridgeConfirmRequest { pub token: String, } /// POST /api/networking/lan-bridge/confirm — confirm a pending /// management-NIC bridge so its auto-revert watchdog does not fire. pub async fn net_lan_bridge_confirm( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let token = body.into_inner().token; match web::block(move || crate::networking::lan_bridge::confirm_lan_bridge(&token)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("confirm task: {}", e) })), } } #[derive(Deserialize)] pub struct DnsSetRequest { pub nameservers: Vec, pub search_domains: Vec, } /// POST /api/networking/dns — set DNS configuration pub async fn net_set_dns( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match networking::set_dns(body.nameservers.clone(), body.search_domains.clone()) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// GET /api/networking/wolfnet — get WolfNet overlay status pub async fn net_get_wolfnet(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // web::block: systemctl subprocesses on systemd hosts, a /proc scan on // Unraid — sync work either way. match web::block(networking::get_wolfnet_status).await { Ok(status) => HttpResponse::Ok().json(status), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("WolfNet status worker failed: {}", e) })), } } /// GET /api/networking/wolfnet/config — get raw WolfNet config pub async fn net_get_wolfnet_config(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match networking::get_wolfnet_config() { Ok(config) => HttpResponse::Ok().json(serde_json::json!({"config": config})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct WolfNetConfigSave { pub config: String, } /// PUT /api/networking/wolfnet/config — save raw WolfNet config pub async fn net_save_wolfnet_config(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match networking::save_wolfnet_config(&body.config) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct WolfNetAddPeer { pub name: String, pub endpoint: Option, pub ip: Option, pub public_key: Option, } /// POST /api/networking/wolfnet/peers — add a WolfNet peer pub async fn net_add_wolfnet_peer(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Manual API: a missing/null/empty endpoint means "preserve whatever // the existing peer has" so a third-party script PATCHing other // fields doesn't accidentally wipe a working endpoint. The cluster- // sync code uses a different inbound endpoint marker (`__clear__`) // when it specifically wants to remove a stale unreachable endpoint. let endpoint = match body.endpoint.as_deref() { Some("__clear__") => networking::PeerEndpoint::Clear, Some(s) if !s.is_empty() => networking::PeerEndpoint::Set(s.to_string()), _ => networking::PeerEndpoint::Preserve, }; let ip = body.ip.as_deref().unwrap_or(""); let public_key = body.public_key.as_deref(); match networking::add_wolfnet_peer(&body.name, endpoint, ip, public_key) { Ok(msg) => { let local_info = networking::get_wolfnet_local_info(); HttpResponse::Ok().json(serde_json::json!({ "message": msg, "local_info": local_info, })) }, Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct WolfNetEditPeer { /// The peer's CURRENT name (locates the entry to edit). pub old_name: String, /// New name (may equal old_name when only other fields change). pub name: String, /// WYSIWYG: a value pins the endpoint; empty/absent = auto-discovery (clear). pub endpoint: Option, pub ip: Option, /// Empty/absent keeps the current key. pub public_key: Option, } /// PUT /api/networking/wolfnet/peers — edit an existing WolfNet peer. pub async fn net_edit_wolfnet_peer(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let old_name = body.old_name.clone(); let new_name = body.name.clone(); if new_name.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Peer name is required"})); } // Edit is WYSIWYG (see edit_wolfnet_peer): an emptied endpoint field means // "make this peer auto-discovery", so empty maps to Clear (not Preserve). let endpoint = match body.endpoint.as_deref() { Some(s) if !s.is_empty() => networking::PeerEndpoint::Set(s.to_string()), _ => networking::PeerEndpoint::Clear, }; let ip = body.ip.clone().unwrap_or_default(); let public_key = body.public_key.clone(); // Offload the blocking config read-modify-write + wolfnet reload/restart // (it shells out and sleeps) off the actix worker. let result = web::block(move || { networking::edit_wolfnet_peer(&old_name, &new_name, &ip, endpoint, public_key.as_deref()) }).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("edit task failed: {}", e)})), } } /// GET /api/networking/wolfnet/local-info — get this node's WolfNet identity pub async fn net_get_wolfnet_local_info(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match networking::get_wolfnet_local_info() { Some(info) => HttpResponse::Ok().json(info), None => HttpResponse::Ok().json(serde_json::json!({"error": "WolfNet not running or status unavailable"})), } } #[derive(Deserialize)] pub struct WolfNetRemovePeer { pub name: String, } /// DELETE /api/networking/wolfnet/peers — remove a WolfNet peer pub async fn net_remove_wolfnet_peer(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Capture the peer's wolfnet IP BEFORE removal so the subnet-route // cleanup below has a gateway to match against. After remove_wolfnet_peer // the entry is gone from the config and the lookup would return None. let peer_wn_ip: Option = networking::get_wolfnet_peers_list() .into_iter() .find(|p| p.name == body.name) .map(|p| p.ip.split('/').next().unwrap_or(&p.ip).to_string()); match networking::remove_wolfnet_peer(&body.name) { Ok(msg) => { // Tear down any subnet_routes pointing through this peer. // Auto-installed routes outlive the wolfnet peer entry // otherwise, and the kernel keeps tunnelling packets to a // dead gateway (klasSponsor 2026-05-12 — the 19 GB outbound // burst was traffic following auto-applied routes whose // gateways were peers he'd already removed). let subnet_routes_disabled = match peer_wn_ip { Some(ip) => crate::networking::router::disable_subnet_routes_via_gateway(&state.router, &ip), None => 0, }; HttpResponse::Ok().json(serde_json::json!({ "message": msg, "subnet_routes_disabled": subnet_routes_disabled, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// GET /api/networking/wolfnet/tombstones — list operator-tombstoned peer hostnames pub async fn net_wolfnet_tombstones_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(serde_json::json!({ "tombstones": networking::wolfnet_tombstone_list(), })) } #[derive(Deserialize)] pub struct WolfNetTombstoneTarget { pub hostname: String, } /// DELETE /api/networking/wolfnet/tombstones — un-tombstone a hostname so /// the gossip / auto-apply / reconciler paths can re-add it normally on /// next tick. Use this when you want a previously-removed peer back in /// the cluster. pub async fn net_wolfnet_tombstone_remove(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let was_present = networking::wolfnet_tombstone_remove(&body.hostname); HttpResponse::Ok().json(serde_json::json!({ "hostname": body.hostname, "was_tombstoned": was_present, })) } #[derive(Deserialize)] pub struct WolfNetAction { pub action: String, } /// POST /api/networking/wolfnet/action — start/stop/restart WolfNet pub async fn net_wolfnet_action(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let allowed = ["start", "stop", "restart", "enable", "disable"]; if !allowed.contains(&body.action.as_str()) { return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid action"})); } // web::block: systemctl is a subprocess, and the Unraid supervisor path // waits up to five seconds for a clean daemon exit on stop/restart — // neither belongs on an actix worker thread. let action = body.action.clone(); match web::block(move || networking::wolfnet_service_action(&action)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("WolfNet action worker failed: {}", e) })), } } /// GET /api/networking/wolfnet/invite — generate a WolfNet invite token pub async fn net_wolfnet_invite(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match networking::generate_wolfnet_invite() { Ok(invite) => HttpResponse::Ok().json(invite), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// GET /api/networking/wolfnet/status-full — get full status including live peers pub async fn net_wolfnet_status_full(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(networking::get_wolfnet_status_full()) } #[derive(Deserialize)] pub struct IpAction { pub address: String, pub prefix: u32, } /// POST /api/networking/interfaces/{name}/ip — add an IP address pub async fn net_add_ip( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let iface = path.into_inner(); match networking::add_ip(&iface, &body.address, body.prefix) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/networking/interfaces/{name}/ip — remove an IP address pub async fn net_remove_ip( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let iface = path.into_inner(); match networking::remove_ip(&iface, &body.address, body.prefix) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct InterfaceStateAction { pub up: bool, } /// POST /api/networking/interfaces/{name}/state — bring interface up/down pub async fn net_set_state( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let iface = path.into_inner(); match networking::set_interface_state(&iface, body.up) { Ok(msg) => { // Bringing an interface DOWN can strand the admin LAN or // the WAN. Register with the danger framework so the // operator has a countdown-to-auto-up in the UI banner. // Bringing UP is safe — no rollback needed. if !body.up { // Operator chose down: stop re-upping it at boot (back // to whatever the system's own network config does). networking::link_persist::clear(&iface); let iface_for_undo = iface.clone(); let danger_id = crate::danger::schedule( "interface_down", &format!("Interface {} was brought DOWN", iface), 90, Box::new(move || { crate::networking::set_interface_state(&iface_for_undo, true).map(|_| { // The undo restores the runtime state, so it // restores the boot intent too — otherwise a // cancelled down would still lose the NIC at // the next reboot. let note = crate::networking::link_persist::record_up(&iface_for_undo); format!("Interface {} brought back UP{}.", iface_for_undo, note) }) }), ); return HttpResponse::Ok().json(serde_json::json!({ "message": msg, "danger_id": danger_id, "ttl_secs": 90, "confirm_required": true, })); } // UP from the UI is an intent, not a one-off: without this a // NIC no network manager owns (typical USB NIC) is down again // after every reboot (RutgerDiehard, 2026-08-18). let note = networking::link_persist::record_up(&iface); HttpResponse::Ok().json(serde_json::json!({ "message": format!("{}{}", msg, note) })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct MtuAction { pub mtu: u32, } /// POST /api/networking/interfaces/{name}/mtu — set interface MTU pub async fn net_set_mtu( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let iface = path.into_inner(); match networking::set_mtu(&iface, body.mtu) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/networking/vlans/{name} — delete a VLAN pub async fn net_delete_vlan( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); match networking::delete_vlan(&name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── IP Mapping API ─── #[derive(Deserialize)] pub struct CreateIpMappingRequest { pub public_ip: String, pub wolfnet_ip: String, pub ports: Option, pub dest_ports: Option, pub protocol: Option, pub label: Option, } /// GET /api/networking/ip-mappings — list all IP mappings pub async fn net_list_ip_mappings( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(networking::list_ip_mappings()) } /// POST /api/networking/ip-mappings — create an IP mapping pub async fn net_add_ip_mapping( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let protocol = body.protocol.as_deref().unwrap_or("all"); let label = body.label.as_deref().unwrap_or(""); match networking::add_ip_mapping( &body.public_ip, &body.wolfnet_ip, body.ports.as_deref(), body.dest_ports.as_deref(), protocol, label, ) { Ok(mapping) => { let reachability = networking::check_wolfnet_reachability(&mapping.wolfnet_ip); let warning = match reachability { "unreachable" => Some(format!( "Mapping saved, but {} is not reachable over WolfNet from this node. \ iptables rules are in place but packets to this target will be black-holed \ until WolfNet routing to it comes up. Check: WireGuard peer status, the \ target VM/container is running, and the node hosting it is online.", mapping.wolfnet_ip )), "no_wolfnet" => Some( "Mapping saved, but this node has no WolfNet interface — packets cannot \ leave this host via WolfNet. Start WolfNet on this node.".to_string() ), _ => None, }; HttpResponse::Ok().json(serde_json::json!({ "message": format!("Mapped {} → {}", mapping.public_ip, mapping.wolfnet_ip), "mapping": mapping, "reachability": reachability, "warning": warning, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/networking/ip-mappings/{id} — remove an IP mapping pub async fn net_remove_ip_mapping( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match networking::remove_ip_mapping(&id) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// PUT /api/networking/ip-mappings/{id} — update an existing mapping pub async fn net_update_ip_mapping( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let protocol = body.protocol.as_deref().unwrap_or("all"); let label = body.label.as_deref().unwrap_or(""); match networking::update_ip_mapping( &id, &body.public_ip, &body.wolfnet_ip, body.ports.as_deref(), body.dest_ports.as_deref(), protocol, label, ) { Ok(mapping) => { let reachability = networking::check_wolfnet_reachability(&mapping.wolfnet_ip); let warning = match reachability { "unreachable" => Some(format!( "Mapping saved, but {} is not reachable over WolfNet from this node. \ iptables rules are in place but packets to this target will be black-holed \ until WolfNet routing to it comes up. Check: WireGuard peer status, the \ target VM/container is running, and the node hosting it is online.", mapping.wolfnet_ip )), "no_wolfnet" => Some( "Mapping saved, but this node has no WolfNet interface — packets cannot \ leave this host via WolfNet. Start WolfNet on this node.".to_string() ), _ => None, }; HttpResponse::Ok().json(serde_json::json!({ "mapping": mapping, "reachability": reachability, "warning": warning, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/networking/available-ips — detect public + wolfnet IPs for the UI pub async fn net_available_ips( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(serde_json::json!({ "public_ips": networking::detect_public_ips(), "wolfnet_ips": networking::detect_wolfnet_ips(), })) } /// GET /api/networking/listening-ports — ports currently in use on server pub async fn net_listening_ports( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(serde_json::json!({ "listening": networking::get_listening_ports(), "blocked": networking::get_blocked_ports(), })) } // ─── WireGuard Bridge API ─── /// GET /api/networking/wireguard — list all bridges pub async fn net_wireguard_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let bridges = state.wireguard_bridges.read().unwrap(); let installed = networking::wireguard_installed(); let list: Vec = bridges.values().map(|b| { serde_json::json!({ "cluster": b.cluster, "enabled": b.enabled, "listen_port": b.listen_port, "public_key": b.public_key, "bridge_subnet": b.bridge_subnet(), "server_ip": b.server_ip, "wolfnet_subnet": b.wolfnet_subnet, "interface": b.interface_name(), "client_count": b.clients.len(), }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "installed": installed, "bridges": list, })) } /// GET /api/networking/wireguard/{cluster} — get bridge details + clients pub async fn net_wireguard_get(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cluster = path.into_inner(); let bridges = state.wireguard_bridges.read().unwrap(); match bridges.get(&cluster) { Some(bridge) => { let clients: Vec = bridge.clients.iter().map(|c| { serde_json::json!({ "id": c.id, "name": c.name, "public_key": c.public_key, "assigned_ip": c.assigned_ip, "created_at": c.created_at, "enabled": c.enabled, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "cluster": bridge.cluster, "enabled": bridge.enabled, "listen_port": bridge.listen_port, "public_key": bridge.public_key, "bridge_subnet": bridge.bridge_subnet(), "server_ip": bridge.server_ip, "wolfnet_subnet": bridge.wolfnet_subnet, "interface": bridge.interface_name(), "clients": clients, })) } None => HttpResponse::NotFound().json(serde_json::json!({"error": "No bridge for this cluster"})), } } #[derive(Deserialize)] pub struct WgInitRequest { #[serde(default = "default_wg_port")] listen_port: u16, } fn default_wg_port() -> u16 { 51820 } /// POST /api/networking/wireguard/{cluster}/init — initialize bridge pub async fn net_wireguard_init(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cluster = path.into_inner(); match networking::init_wireguard_bridge(&cluster, body.listen_port) { Ok(bridge) => { // Reload the live map from disk (mirrors toggle/delete) so the UI // can never diverge from persisted state — the divergence that hid // klasSponsor's half-created bridge from the WireGuard UI. *state.wireguard_bridges.write().unwrap() = networking::load_wireguard_bridges(); HttpResponse::Ok().json(serde_json::json!({ "status": "ok", "bridge_subnet": bridge.bridge_subnet(), "listen_port": bridge.listen_port, "public_key": bridge.public_key, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct WgToggleRequest { enabled: bool, } /// POST /api/networking/wireguard/{cluster}/toggle — enable/disable bridge pub async fn net_wireguard_toggle(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cluster = path.into_inner(); match networking::toggle_wireguard_bridge(&cluster, body.enabled) { Ok(msg) => { // Reload state let fresh = networking::load_wireguard_bridges(); *state.wireguard_bridges.write().unwrap() = fresh; HttpResponse::Ok().json(serde_json::json!({"status": msg})) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// DELETE /api/networking/wireguard/{cluster} — delete bridge entirely pub async fn net_wireguard_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cluster = path.into_inner(); match networking::delete_wireguard_bridge(&cluster) { Ok(msg) => { state.wireguard_bridges.write().unwrap().remove(&cluster); HttpResponse::Ok().json(serde_json::json!({"status": msg})) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct WgAddClientRequest { name: String, } /// POST /api/networking/wireguard/{cluster}/clients — add client pub async fn net_wireguard_add_client(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cluster = path.into_inner(); match networking::add_wireguard_client(&cluster, &body.name) { Ok((client, conf)) => { // Reload state let fresh = networking::load_wireguard_bridges(); *state.wireguard_bridges.write().unwrap() = fresh; HttpResponse::Ok().json(serde_json::json!({ "client": { "id": client.id, "name": client.name, "assigned_ip": client.assigned_ip, "created_at": client.created_at, }, "config": conf, })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// DELETE /api/networking/wireguard/{cluster}/clients/{id} — remove client pub async fn net_wireguard_remove_client(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (cluster, client_id) = path.into_inner(); match networking::remove_wireguard_client(&cluster, &client_id) { Ok(msg) => { let fresh = networking::load_wireguard_bridges(); *state.wireguard_bridges.write().unwrap() = fresh; HttpResponse::Ok().json(serde_json::json!({"status": msg})) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// GET /api/networking/wireguard/{cluster}/clients/{id}/config — download client config pub async fn net_wireguard_client_config(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (cluster, client_id) = path.into_inner(); match networking::get_client_config(&cluster, &client_id) { Ok(conf) => HttpResponse::Ok() .content_type("text/plain") .insert_header(("Content-Disposition", format!("attachment; filename=\"wg-{}-{}.conf\"", cluster, client_id))) .body(conf), Err(e) => HttpResponse::NotFound().json(serde_json::json!({"error": e})), } } // ─── VLAN / vSwitch / Public-IP attachment API ───────────────────── // // Backed by `crate::networking::vlan`. Lets the operator add/remove // 802.1Q VLAN attachments (Hetzner vSwitch, OVH vRack, Equinix Metal, // generic 802.1Q) and routed extra public IPs without hand-editing // /etc/network/interfaces. /// GET /api/networking/vlan — current store + detected network manager. pub async fn vlan_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Discovery walks container/VM configs and may shell out (qm/virsh) — // keep it off the async workers via web::block. let blk = web::block(|| { let store = crate::networking::vlan::VlanStore::load(); // Guests actually wired to each VLAN's bridge, found live — the // persisted `allocations` only know attachments made through this // page, so pre-existing guests were invisible (RutgerDiehard, // 2026-08-07: an LXC on every vSwitch bridge, none listed). let discovered: std::collections::HashMap> = store.vlans.iter() .map(|v| (v.id.clone(), crate::networking::vlan::discover_bridge_guests(&v.bridge_name))) .collect(); (store, discovered) }).await; let (store, discovered) = match blk { Ok(v) => v, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("could not read VLAN state: {}", e), })), }; let manager = crate::networking::vlan::detect_net_manager(); HttpResponse::Ok().json(serde_json::json!({ "vlans": store.vlans, "discovered": discovered, "public_ips": store.public_ips, "net_manager": manager, "net_manager_label": manager.label(), "auto_persist_supported": manager.auto_persist_supported(), })) } /// POST /api/networking/vlan/attachments — create or update a VLAN /// attachment. Body is the full `VlanAttachment` (id may be empty for /// create — server generates one). /// /// Preflight gate: by default, refuses to save when `preflight` reports /// any `critical` findings. The frontend calls `/api/networking/vlan/preflight` /// first, shows the operator the findings, and re-submits with /// `?ack_critical=true` after they confirm. This is the safety net that /// stops a typo'd parent NIC or duplicate bridge from silently breaking /// the operator's network. #[derive(Deserialize, Default)] pub struct VlanUpsertQuery { #[serde(default)] pub ack_critical: bool, } pub async fn vlan_upsert( req: HttpRequest, state: web::Data, body: web::Json, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let proposed = body.into_inner(); // Preflight before we mutate state. Re-run server-side even though // the frontend likely already showed the operator the same findings — // the host could have changed between preflight and submit. let store_for_check = crate::networking::vlan::VlanStore::load(); let manager = crate::networking::vlan::detect_net_manager(); let findings = crate::networking::vlan::preflight(&store_for_check, manager, Some(&proposed)); let critical: Vec<_> = findings.iter() .filter(|f| matches!(f.severity, crate::networking::vlan::PreflightSeverity::Critical)) .cloned() .collect(); if !critical.is_empty() && !query.ack_critical { return HttpResponse::Conflict().json(serde_json::json!({ "error": "preflight reported critical findings; pass ?ack_critical=true to apply anyway", "preflight": findings, })); } let mut store = store_for_check; let id = match store.upsert_vlan(proposed) { Ok(id) => id, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Apply immediately so the operator sees the live result. Failures // here are surfaced but don't fail the save — the persisted state // is still valid and the UI can show what went wrong. let report = match crate::networking::vlan::apply(&store) { Ok(r) => r, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("saved but apply failed: {}", e), "id": id, "preflight": findings, })), }; HttpResponse::Ok().json(serde_json::json!({ "id": id, "apply": report, "preflight": findings, })) } /// DELETE /api/networking/vlan/attachments/{id} — remove and tear down. pub async fn vlan_remove( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let mut store = crate::networking::vlan::VlanStore::load(); let target = store.get_vlan(&id).cloned(); if !store.remove_vlan(&id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("vlan attachment '{}' not found", id), })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Tear down the kernel state for the removed VLAN before // re-applying the rest, so we don't leave orphan devices. if let Some(t) = target { crate::networking::vlan::teardown_vlan_kernel_state(&t.parent_iface, t.vlan_id, &t.bridge_name); } let _ = crate::networking::vlan::apply(&store); HttpResponse::Ok().json(serde_json::json!({ "removed": true })) } /// POST /api/networking/vlan/public-ips — create or update a routed /// public IP attachment. pub async fn public_ip_upsert( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mut store = crate::networking::vlan::VlanStore::load(); let id = match store.upsert_public_ip(body.into_inner()) { Ok(id) => id, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let report = match crate::networking::vlan::apply(&store) { Ok(r) => r, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("saved but apply failed: {}", e), "id": id, })), }; HttpResponse::Ok().json(serde_json::json!({ "id": id, "apply": report })) } /// DELETE /api/networking/vlan/public-ips/{id} — remove and tear down /// iptables/lo state for a routed public IP. pub async fn public_ip_remove( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let mut store = crate::networking::vlan::VlanStore::load(); let target = store.get_public_ip(&id).cloned(); if !store.remove_public_ip(&id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("public ip attachment '{}' not found", id), })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } if let Some(t) = target { crate::networking::vlan::teardown_public_ip_kernel_state(&t.ip, &t.container_internal_ip, &t.egress_iface); } let _ = crate::networking::vlan::apply(&store); HttpResponse::Ok().json(serde_json::json!({ "removed": true })) } /// POST /api/networking/vlan/apply — re-apply the entire store. /// Useful as an "I edited the JSON by hand, please reconcile" button /// or after a fresh boot if persistence wasn't perfect. pub async fn vlan_apply(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let store = crate::networking::vlan::VlanStore::load(); match crate::networking::vlan::apply(&store) { Ok(report) => HttpResponse::Ok().json(report), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/networking/vlan/preview — dry-run rendering of the current /// store. Lets the UI show the operator the config snippet that would /// be written before they hit save. Now also runs preflight against /// the live host so the operator sees disruption warnings up-front. pub async fn vlan_preview(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let store = crate::networking::vlan::VlanStore::load(); let snippet = crate::networking::vlan::render_ifupdown(&store); let manager = crate::networking::vlan::detect_net_manager(); let preflight = crate::networking::vlan::preflight(&store, manager, None); HttpResponse::Ok().json(serde_json::json!({ "snippet": snippet, "manager": manager, "preflight": preflight, })) } /// POST /api/networking/vlan/parse-config — parse a pasted /// `/etc/network/interfaces` from another server and return any VLAN /// definitions found. Used by the "import from another server" flow: /// operator copies a working config from machine A and uses the parsed /// values as a template for machine B. #[derive(Deserialize)] pub struct ParseConfigRequest { /// For now, only "ifupdown" is supported. Future: netplan, networkd. #[serde(default)] pub format: String, pub content: String, } pub async fn vlan_parse_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); // Default to ifupdown if format is empty/unknown — that's the only // parser we have today and the user's pasting Debian-style config. let parsed = if body.format.is_empty() || body.format == "ifupdown" { crate::networking::vlan::parse_ifupdown_text(&body.content) } else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unsupported config format '{}'; only 'ifupdown' is supported in this version", body.format), })); }; HttpResponse::Ok().json(serde_json::json!({ "parsed": parsed })) } // ──────────────────────────────────────────────────────────────────── // Emergency security actions // ──────────────────────────────────────────────────────────────────── /// POST /api/security/rotate-root-local — rotate THIS node's root /// password and return the new password to the caller. Designed to be /// invoked either: /// - directly by a logged-in operator (via the UI on this node) /// - by another WolfStack node acting as a fleet-rotation coordinator /// (via X-WolfStack-Secret auth) /// /// The password is generated locally with the system CSPRNG. It is /// also appended to /root/.wolfstack-emergency-passwords.txt (mode /// 0600) as a belt-and-braces backup in case the UI display fails. /// Existing SSH sessions for root are killed so any active attacker /// session drops at the same moment. pub async fn security_rotate_root_local( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let result = tokio::task::spawn_blocking(crate::security::rotate_local_root).await; match result { Ok(Ok(pw)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "password": pw, "hostname": hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_default(), })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": e, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": format!("rotation task panicked: {}", e), })), } } #[derive(Deserialize)] pub struct FleetRotateRequest { /// Operator typed confirmation phrase — must equal "ROTATE ALL PASSWORDS". /// Defense against accidental clicks; the UI requires this be typed /// before enabling the submit button. pub confirmation: String, /// If true, also rotate the coordinator node's own password. Defaults /// to true. Set false if the operator wants to rotate peers first /// (e.g. they're SSH'd into the coordinator and want to keep that /// session alive a bit longer). #[serde(default = "default_true_include_self")] pub include_self: bool, } fn default_true_include_self() -> bool { true } #[derive(Serialize)] pub struct FleetRotateNodeResult { pub node_id: String, pub hostname: String, pub address: String, pub node_type: String, pub status: String, // "ok" | "failed" | "skipped" pub new_password: Option, pub error: Option, } /// POST /api/security/rotate-fleet — coordinator endpoint. Fans the /// rotation out to every WolfStack-managed node in the cluster /// (including this one if include_self=true), collects results, and /// returns the per-node passwords ONCE. The operator MUST save them /// immediately — they're not stored anywhere else in WolfStack's state. /// /// Proxmox-only nodes (where WolfStack isn't installed) are surfaced /// as "skipped" with a hint that the operator must rotate via the /// Proxmox UI or SSH. pub async fn security_rotate_fleet( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); if body.confirmation.trim() != "ROTATE ALL PASSWORDS" { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "confirmation phrase must equal 'ROTATE ALL PASSWORDS' exactly", })); } // Snapshot the cluster state so we don't hold the lock across async work. let (self_id, nodes) = { let n = state.cluster.nodes_read(); (state.cluster.self_id.clone(), n.values().cloned().collect::>()) }; let secret = state.cluster_secret.clone(); let mut futures = Vec::new(); for node in nodes { let secret_c = secret.clone(); let self_id_c = self_id.clone(); let include_self = body.include_self; futures.push(async move { let is_self = node.id == self_id_c; // Proxmox-only nodes can't be remotely rotated by us — // surface as skipped with a clear instruction. if node.node_type != "wolfstack" { return FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "skipped".into(), new_password: None, error: Some("Proxmox-only node — WolfStack agent not installed. Rotate manually via Proxmox UI or SSH.".into()), }; } if is_self && !include_self { return FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "skipped".into(), new_password: None, error: Some("Skipped (include_self=false). Rotate this node manually when ready.".into()), }; } // For self, run rotation in-process — avoids the loopback HTTP // call and the risk that the coordinator's own SSH session // (if any) gets killed before the rotation completes. if is_self { match tokio::task::spawn_blocking(crate::security::rotate_local_root).await { Ok(Ok(pw)) => FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "ok".into(), new_password: Some(pw), error: None, }, Ok(Err(e)) => FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "failed".into(), new_password: None, error: Some(e), }, Err(e) => FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "failed".into(), new_password: None, error: Some(format!("panic: {}", e)), }, } } else { // Remote peer — call its /api/security/rotate-root-local // with the cluster secret using the canonical HTTPS-first // chain. let urls = build_node_urls(&node.address, node.port, "/api/security/rotate-root-local"); // Shared pooled inter-node client (identical TLS policy). A // fresh per-call client leaked a connection pool per node. let client = &*API_HTTP_CLIENT; let mut last_err = String::new(); for url in &urls { let resp = client.post(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&secret_c) .send().await; match resp { Ok(r) if r.status().is_success() => { if let Ok(j) = r.json::().await { let pw = j.get("password").and_then(|v| v.as_str()).map(|s| s.to_string()); return FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "ok".into(), new_password: pw, error: None, }; } last_err = "remote returned 200 but no parseable JSON".into(); } Ok(r) => { let status = r.status(); drain_response(r).await; last_err = format!("HTTP {}", status); } Err(e) => { last_err = format!("transport: {}", e); } } } FleetRotateNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, node_type: node.node_type, status: "failed".into(), new_password: None, error: Some(format!("all transports failed; last: {}", last_err)), } } }); } let results = futures::future::join_all(futures).await; let ok = results.iter().filter(|r| r.status == "ok").count(); let failed = results.iter().filter(|r| r.status == "failed").count(); let skipped = results.iter().filter(|r| r.status == "skipped").count(); HttpResponse::Ok().json(serde_json::json!({ "summary": format!("{} rotated, {} failed, {} skipped", ok, failed, skipped), "results": results, "important": "These passwords are NOT stored anywhere in WolfStack. Save them to your password manager immediately. Each node also has a backup at /root/.wolfstack-emergency-passwords.txt (mode 0600).", })) } // ════════════════════════════════════════════════════════════════════ // Fleet-wide aggregation endpoints — power the Fleet Security page. // Each endpoint fans out to every WolfStack peer in the cluster, // collects responses in parallel, and returns a structured per-node // view that the UI can render as a unified table. // ════════════════════════════════════════════════════════════════════ #[derive(Serialize)] pub struct FleetNodeResult { pub node_id: String, pub hostname: String, pub address: String, pub status: String, // "ok" | "failed" | "skipped" pub data: Option, pub error: Option, } /// Fan out an authenticated GET to every WolfStack peer (including /// self) and collect each one's JSON response. Self is handled /// in-process via the supplied `local` closure to avoid the loopback /// round-trip. async fn fleet_fanout_get( state: &web::Data, path: &str, local: Local, ) -> Vec> where T: serde::de::DeserializeOwned + Serialize + Send + 'static, Local: FnOnce() -> T, { let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values().cloned().collect(); (self_id, peers) }; let secret = state.cluster_secret.clone(); let local_result = std::sync::Mutex::new(Some(local())); let mut tasks = Vec::new(); for node in peers { let is_self = node.id == self_id; let secret_c = secret.clone(); let path = path.to_string(); let local_ref = if is_self { let mut g = local_result.lock().unwrap(); g.take() } else { None }; tasks.push(async move { if let Some(data) = local_ref { return FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "ok".into(), data: Some(data), error: None, }; } if node.node_type != "wolfstack" { return FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "skipped".into(), data: None, error: Some("non-WolfStack node".into()), }; } let urls = build_node_urls(&node.address, node.port, &path); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; // Capture WHY each attempt failed. We collect EVERY url's // error rather than overwriting — otherwise the operator // only sees the last attempt's failure and the actual root // cause on the primary URL (HTTPS) stays hidden. let mut errors: Vec = Vec::new(); for url in &urls { let resp = client.get(url).timeout(std::time::Duration::from_secs(8)).peer_auth(&secret_c).send().await; match resp { Ok(r) if r.status().is_success() => { match r.json::().await { Ok(v) => return FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "ok".into(), data: Some(v), error: None, }, Err(e) => { errors.push(format!("{} -> 200 OK but JSON parse failed: {}", url, e)); } } } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); let preview = body.chars().take(200).collect::(); errors.push(format!("{} -> HTTP {}: {}", url, status, preview)); } Err(e) => { errors.push(format!("{} -> transport: {}", url, e)); } } } FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "failed".into(), data: None, error: Some(errors.join(" | ")), } }); } futures::future::join_all(tasks).await } // ════════════════════════════════════════════════════════════════════ // Authorised keys — root SSH keys, per host or fleet-wide. // // Every mutation re-anchors the tamper-detection baseline in the same // operation (see ssh_keys::write_authorized_keys), so a key added // here never surfaces as drift. That is the point of the feature: it // gives operators a sanctioned path, which in turn lets // predictive::tamper_detection treat every REMAINING authorized_keys // change as genuinely out-of-band. // ════════════════════════════════════════════════════════════════════ #[derive(Serialize, Deserialize)] pub struct SshKeyListResponse { pub keys: Vec, /// Entries present in the file that this manager doesn't model /// (options-carrying lines, CA delegations). Counted so the UI can /// say "2 entries not shown" instead of implying the list is the /// whole file. pub unmanaged_entries: usize, pub sshd: crate::ssh_keys::SshdKeyPosture, } #[derive(Serialize, Deserialize)] pub struct SshKeyMutationResult { /// "added" | "unchanged" | "removed" pub outcome: String, pub fingerprint: String, } #[derive(Deserialize)] pub struct SshKeyAddRequest { pub public_key: String, #[serde(default)] pub label: String, /// Set by a coordinating peer so the audit trail names the human /// who started the fleet operation rather than just "cluster-node". #[serde(default)] pub actor: String, } #[derive(Deserialize)] pub struct SshKeyRemoveRequest { pub fingerprint: String, #[serde(default)] pub force: bool, #[serde(default)] pub actor: String, } #[derive(Deserialize)] pub struct SshKeyFleetAddRequest { pub public_key: String, #[serde(default)] pub label: String, /// Empty means every WolfStack node in this cluster. #[serde(default)] pub targets: Vec, } #[derive(Deserialize)] pub struct SshKeyFleetRemoveRequest { pub fingerprint: String, #[serde(default)] pub targets: Vec, #[serde(default)] pub force: bool, } /// Who to record as having made the change. /// /// A peer authenticates as "cluster-node", which on its own would /// make every fleet operation anonymous in the baseline audit trail. /// When the caller is a peer we therefore accept the operator name it /// forwarded — the peer already holds the cluster secret, so this /// grants no new authority, it just keeps the trail honest. The value /// is sanitised because it lands in a JSON file on disk. fn resolve_key_actor(auth_user: &str, forwarded: &str) -> String { if auth_user != "cluster-node" || forwarded.trim().is_empty() { return auth_user.to_string(); } let clean: String = forwarded .chars() .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '@')) .take(64) .collect(); if clean.is_empty() { auth_user.to_string() } else { format!("{} (via cluster)", clean) } } // ═══════════════════════════════════════════════════ // ─── Wake-on-LAN ─── // ═══════════════════════════════════════════════════ // // Every endpoint acts on THIS node's targets only. The cluster page // reaches each node through /api/nodes/{id}/proxy, so a Wake click is // sent by the node on the target's LAN. Changes and wakes use // require_operator_auth: it refuses viewers and a bare cluster secret, // and names the operator behind a proxied call for the log line. fn wol_error(status: actix_web::http::StatusCode, e: impl Into) -> HttpResponse { HttpResponse::build(status).json(serde_json::json!({ "error": e.into() })) } fn wol_task_panicked(e: tokio::task::JoinError) -> HttpResponse { wol_error(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR, format!("wake-on-lan task failed: {}", e)) } /// GET /api/wol/targets — this node's Wake-on-LAN targets. pub async fn wol_targets_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match tokio::task::spawn_blocking(crate::wol::load).await { Ok(cfg) => HttpResponse::Ok().json(serde_json::json!({ "targets": cfg.targets })), Err(e) => wol_task_panicked(e), } } /// GET /api/wol/status — ping every target that has a host set, from /// this node, in parallel. `{ "": true | false | null }`, null = /// no host configured. pub async fn wol_targets_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = match tokio::task::spawn_blocking(crate::wol::load).await { Ok(c) => c, Err(e) => return wol_task_panicked(e), }; let checks = cfg.targets.iter().map(|t| async move { (t.id.clone(), crate::wol::is_up(t).await) }); let statuses: serde_json::Map = futures::future::join_all(checks).await.into_iter() .map(|(id, up)| (id, serde_json::json!(up))) .collect(); HttpResponse::Ok().json(statuses) } /// POST /api/wol/targets — add a target to this node. pub async fn wol_targets_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let actor = match require_operator_auth(&req, &state) { Ok(a) => a, Err(e) => return e }; let input = body.into_inner(); match tokio::task::spawn_blocking(move || crate::wol::add(&input)).await { Ok(Ok(t)) => { tracing::info!("wol: '{}' added target '{}' ({})", actor, t.name, t.mac); HttpResponse::Ok().json(t) } Ok(Err(e)) => wol_error(actix_web::http::StatusCode::BAD_REQUEST, e), Err(e) => wol_task_panicked(e), } } /// PUT /api/wol/targets/{id} — edit a target on this node. pub async fn wol_targets_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { let actor = match require_operator_auth(&req, &state) { Ok(a) => a, Err(e) => return e }; let id = path.into_inner(); let input = body.into_inner(); match tokio::task::spawn_blocking(move || crate::wol::update(&id, &input)).await { Ok(Ok(t)) => { tracing::info!("wol: '{}' updated target '{}' ({})", actor, t.name, t.mac); HttpResponse::Ok().json(t) } Ok(Err(e)) if e == "target not found" => wol_error(actix_web::http::StatusCode::NOT_FOUND, e), Ok(Err(e)) => wol_error(actix_web::http::StatusCode::BAD_REQUEST, e), Err(e) => wol_task_panicked(e), } } /// DELETE /api/wol/targets/{id} — remove a target from this node. pub async fn wol_targets_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let actor = match require_operator_auth(&req, &state) { Ok(a) => a, Err(e) => return e }; let id = path.into_inner(); match tokio::task::spawn_blocking(move || crate::wol::remove(&id)).await { Ok(Ok(t)) => { tracing::info!("wol: '{}' removed target '{}' ({})", actor, t.name, t.mac); HttpResponse::Ok().json(serde_json::json!({ "deleted": t.id })) } Ok(Err(e)) if e == "target not found" => wol_error(actix_web::http::StatusCode::NOT_FOUND, e), Ok(Err(e)) => wol_error(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR, e), Err(e) => wol_task_panicked(e), } } /// POST /api/wol/targets/{id}/wake — send the magic packet from this /// node. Success means the packet left this node; whether the machine /// woke is what GET /api/wol/status then shows. pub async fn wol_targets_wake( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let actor = match require_operator_auth(&req, &state) { Ok(a) => a, Err(e) => return e }; let id = path.into_inner(); // Err carries (is_not_found, message) so the two failures map to 404 / 500. let outcome = tokio::task::spawn_blocking(move || { let target = crate::wol::load().targets.into_iter().find(|t| t.id == id) .ok_or_else(|| (true, "target not found".to_string()))?; crate::wol::wake(&target).map(|r| (target.name, r)).map_err(|e| (false, e)) }).await; match outcome { Ok(Ok((name, r))) => { tracing::info!("wol: '{}' woke '{}' ({}) via {} on port {}", actor, name, r.mac, r.sent_to.join(", "), r.port); HttpResponse::Ok().json(r) } Ok(Err((true, e))) => wol_error(actix_web::http::StatusCode::NOT_FOUND, e), Ok(Err((false, e))) => { tracing::warn!("wol: '{}' wake failed: {}", actor, e); wol_error(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR, e) } Err(e) => wol_task_panicked(e), } } /// GET /api/ssh-keys — root's authorised keys on THIS node. pub async fn ssh_keys_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match tokio::task::spawn_blocking(ssh_keys_list_local).await { Ok(Ok(r)) => HttpResponse::Ok().json(r), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("list task panicked: {}", e) })), } } /// Blocking body of the list — file read plus `sshd -T`. fn ssh_keys_list_local() -> Result { let (keys, unmanaged_entries) = crate::ssh_keys::list_root_keys()?; Ok(SshKeyListResponse { keys, unmanaged_entries, sshd: crate::ssh_keys::sshd_key_posture(), }) } /// POST /api/ssh-keys/add-local — authorise a key on THIS node. /// Callable by an operator directly or by a fleet coordinator. pub async fn ssh_keys_add_local( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(e) => return e }; let body = body.into_inner(); let actor = resolve_key_actor(&user, &body.actor); // Validate before dispatching to the blocking pool so a bad paste // comes back as a 400, not a 500. let key = match crate::ssh_keys::validate(&body.public_key, &body.label) { Ok(k) => k, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; match tokio::task::spawn_blocking(move || ssh_keys_add_blocking(key, actor)).await { Ok(Ok(r)) => HttpResponse::Ok().json(r), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("add task panicked: {}", e) })), } } fn ssh_keys_add_blocking( key: crate::ssh_keys::PublicKey, actor: String, ) -> Result { let fingerprint = key.fingerprint(); let outcome = crate::ssh_keys::add_root_key(&key, &actor)?; Ok(SshKeyMutationResult { outcome: match outcome { crate::ssh_keys::AddOutcome::Added => "added".into(), crate::ssh_keys::AddOutcome::AlreadyPresent => "unchanged".into(), }, fingerprint, }) } /// POST /api/ssh-keys/remove-local — de-authorise a key on THIS node. pub async fn ssh_keys_remove_local( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(e) => return e }; let body = body.into_inner(); let actor = resolve_key_actor(&user, &body.actor); let fp = body.fingerprint.clone(); let force = body.force; match tokio::task::spawn_blocking(move || ssh_keys_remove_blocking(fp, actor, force)).await { Ok(Ok(r)) => HttpResponse::Ok().json(r), // The lockout refusal is a considered "no", not a server fault — // 409 so the UI can style it as a blocked action rather than an // error to retry. Ok(Err(e)) if e.starts_with("REFUSED") => HttpResponse::Conflict().json(serde_json::json!({ "error": e })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("remove task panicked: {}", e) })), } } fn ssh_keys_remove_blocking( fingerprint: String, actor: String, force: bool, ) -> Result { crate::ssh_keys::remove_root_key(&fingerprint, &actor, force)?; Ok(SshKeyMutationResult { outcome: "removed".into(), fingerprint }) } /// True when `targets` includes this node (or targets everything). fn self_is_targeted(state: &web::Data, targets: &[String]) -> bool { if targets.is_empty() { return true; } let self_id = state.cluster.self_id.clone(); targets.contains(&self_id) } /// GET /api/ssh-keys/fleet — every node's authorised keys, plus a /// merged per-key view of which nodes hold it. pub async fn ssh_keys_fleet_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Compute this node's answer off the executor, then hand the // ready value to the fan-out. let local = tokio::task::spawn_blocking(ssh_keys_list_local).await .unwrap_or_else(|e| Err(format!("list task panicked: {}", e))); let local_for_fanout = local.unwrap_or_else(|e| { tracing::warn!("ssh_keys: local key list failed during fleet fan-out: {}", e); SshKeyListResponse { keys: Vec::new(), unmanaged_entries: 0, sshd: crate::ssh_keys::sshd_key_posture(), } }); let nodes = fleet_fanout_get::( &state, "/api/ssh-keys", move || local_for_fanout, ).await; // Merge by fingerprint. `missing_on` lists only nodes that // actually answered — a node we couldn't reach is unknown, not // missing, and claiming otherwise would invite someone to "fix" // a gap that isn't there. let mut merged: std::collections::BTreeMap = Default::default(); let answered: Vec<&FleetNodeResult> = nodes.iter().filter(|n| n.status == "ok" && n.data.is_some()).collect(); for n in &answered { for k in &n.data.as_ref().unwrap().keys { merged.entry(k.fingerprint.clone()).or_insert_with(|| serde_json::json!({ "fingerprint": k.fingerprint, "key_type": k.key_type, "comment": k.comment, "present_on": [], "missing_on": [], })); } } for (fp, entry) in merged.iter_mut() { let mut present = Vec::new(); let mut missing = Vec::new(); for n in &answered { let has = n.data.as_ref().unwrap().keys.iter().any(|k| k.fingerprint == *fp); let who = serde_json::json!({ "node_id": n.node_id, "hostname": n.hostname }); if has { present.push(who); } else { missing.push(who); } } entry["present_on"] = serde_json::Value::Array(present); entry["missing_on"] = serde_json::Value::Array(missing); } HttpResponse::Ok().json(serde_json::json!({ "nodes": nodes, "keys": merged.into_values().collect::>(), "nodes_answered": answered.len(), // Lets the UI label "this server" without a second round-trip. "self_id": state.cluster.self_id.clone(), })) } /// POST /api/ssh-keys/add-fleet — authorise one key across the /// selected nodes (default: all). pub async fn ssh_keys_add_fleet( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(e) => return e }; let body = body.into_inner(); // Validate once, here, so an invalid key fails as a single clear // 400 instead of an identical failure repeated on every node. let key = match crate::ssh_keys::validate(&body.public_key, &body.label) { Ok(k) => k, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let local = if self_is_targeted(&state, &body.targets) { let k = key.clone(); let a = user.clone(); Some(tokio::task::spawn_blocking(move || ssh_keys_add_blocking(k, a)).await .unwrap_or_else(|e| Err(format!("add task panicked: {}", e)))) } else { None }; // Peers receive the canonical rendered key, not the operator's raw // paste, so every node stores byte-identical material. let peer_body = serde_json::json!({ "public_key": key.to_line(), "label": key.comment, "actor": user, }); let results = fleet_fanout_post::( &state, "/api/ssh-keys/add-local", peer_body, &body.targets, local, FANOUT_QUICK, ).await; HttpResponse::Ok().json(ssh_keys_fleet_summary(results, &key.fingerprint())) } /// POST /api/ssh-keys/remove-fleet — de-authorise one key across the /// selected nodes (default: all). pub async fn ssh_keys_remove_fleet( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(e) => return e }; let body = body.into_inner(); if body.fingerprint.is_empty() || !body.fingerprint.chars().all(|c| c.is_ascii_hexdigit()) { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "Invalid key fingerprint" })); } let local = if self_is_targeted(&state, &body.targets) { let fp = body.fingerprint.clone(); let a = user.clone(); let force = body.force; Some(tokio::task::spawn_blocking(move || ssh_keys_remove_blocking(fp, a, force)).await .unwrap_or_else(|e| Err(format!("remove task panicked: {}", e)))) } else { None }; let peer_body = serde_json::json!({ "fingerprint": body.fingerprint, "force": body.force, "actor": user, }); let results = fleet_fanout_post::( &state, "/api/ssh-keys/remove-local", peer_body, &body.targets, local, FANOUT_QUICK, ).await; HttpResponse::Ok().json(ssh_keys_fleet_summary(results, &body.fingerprint)) } /// Shared response shape for both fleet mutations. /// /// The summary counts "not found on this host" as its own outcome /// rather than a failure: removing a key fleet-wide when only three /// nodes had it is a complete success, and reporting three failures /// would send the operator chasing nothing. fn ssh_keys_fleet_summary( results: Vec>, fingerprint: &str, ) -> serde_json::Value { let changed = results.iter() .filter(|r| r.data.as_ref().is_some_and(|d| d.outcome == "added" || d.outcome == "removed")) .count(); let unchanged = results.iter() .filter(|r| r.data.as_ref().is_some_and(|d| d.outcome == "unchanged")) .count(); let not_present = results.iter() .filter(|r| r.status == "failed" && r.error.as_deref().is_some_and(|e| e.contains("No key with that fingerprint"))) .count(); let failed = results.iter().filter(|r| r.status == "failed").count() - not_present; let skipped = results.iter().filter(|r| r.status == "skipped").count(); serde_json::json!({ "fingerprint": fingerprint, "summary": format!( "{} changed, {} already matched, {} without the key, {} failed, {} skipped", changed, unchanged, not_present, failed, skipped, ), "changed": changed, "unchanged": unchanged, "not_present": not_present, "failed": failed, "skipped": skipped, "results": results, }) } /// GET /api/fleet/security/lockouts — aggregated blocked-IP view /// across every WolfStack node in this cluster AND every federated /// cluster registered here. UI uses this to power the "Fleet blocked /// IPs" + "Last N blocked" panels on the Fleet Security page. Each /// federation is fetched in parallel using its stored api_key as a /// Bearer token; failures are surfaced per-federation so the operator /// can see which one is unreachable without blocking the whole view. pub async fn fleet_security_lockouts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let limiter = state.login_limiter.clone(); let local = move || { serde_json::json!({ "lockouts": limiter.current_lockouts().into_iter().map(|(ip, secs, user)| { serde_json::json!({ "ip": ip, "remaining_seconds": secs, "last_username": user }) }).collect::>(), "audit": limiter.audit_log(), "config": limiter.config(), }) }; // Cluster fanout: every WolfStack peer in this cluster. let cluster_results = fleet_fanout_get::( &state, "/api/security/auth-lockouts", local, ).await; // Federation fanout: every registered federation, in parallel. let federation_results = fetch_federation_lockouts(&state).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": cluster_results, "federations": federation_results, })) } /// Per-federation lockout snapshot used by `fleet_security_lockouts`. #[derive(Serialize)] struct FederationLockoutResult { /// Federation identifier (matches the `id` in FederationStore). federation_id: String, /// Operator-friendly name shown in the UI. name: String, /// Federation's base URL (informational). base_url: String, /// "ok" | "failed" — top-level transport status. status: String, /// Same payload shape as a single cluster node's response: /// `{ lockouts: [...], audit: [...], config: {...} }`. None when /// status != "ok". #[serde(skip_serializing_if = "Option::is_none")] data: Option, #[serde(skip_serializing_if = "Option::is_none")] error: Option, } async fn fetch_federation_lockouts(state: &web::Data) -> Vec { let federations: Vec = match state.federations.read() { Ok(g) => g.clusters.clone(), Err(_) => return Vec::new(), }; if federations.is_empty() { return Vec::new(); } let mut tasks = Vec::new(); for fed in federations { tasks.push(async move { let client = match reqwest::Client::builder() // Bound the CONNECT — see tests/resource_safety.rs .connect_timeout(std::time::Duration::from_secs(5)) .danger_accept_invalid_certs(fed.insecure_tls) .timeout(std::time::Duration::from_secs(8)) .build() { Ok(c) => c, Err(e) => return FederationLockoutResult { federation_id: fed.id.clone(), name: fed.name.clone(), base_url: fed.base_url.clone(), status: "failed".into(), data: None, error: Some(format!("client build: {}", e)), }, }; let url = format!("{}/api/security/auth-lockouts", fed.base_url.trim_end_matches('/')); let resp = client.get(&url) .header("Authorization", format!("Bearer {}", fed.api_key)) .send().await; match resp { Ok(r) if r.status().is_success() => match r.json::().await { Ok(v) => FederationLockoutResult { federation_id: fed.id.clone(), name: fed.name.clone(), base_url: fed.base_url.clone(), status: "ok".into(), data: Some(v), error: None, }, Err(e) => FederationLockoutResult { federation_id: fed.id.clone(), name: fed.name.clone(), base_url: fed.base_url.clone(), status: "failed".into(), data: None, error: Some(format!("200 OK but JSON parse failed: {}", e)), }, }, Ok(r) => { let status_code = r.status(); let body = r.text().await.unwrap_or_default(); FederationLockoutResult { federation_id: fed.id.clone(), name: fed.name.clone(), base_url: fed.base_url.clone(), status: "failed".into(), data: None, error: Some(format!("HTTP {}: {}", status_code, body.chars().take(200).collect::())), } } Err(e) => FederationLockoutResult { federation_id: fed.id.clone(), name: fed.name.clone(), base_url: fed.base_url.clone(), status: "failed".into(), data: None, error: Some(format!("transport: {}", e)), }, } }); } futures::future::join_all(tasks).await } /// GET /api/fleet/security/listening-ports — what's listening on /// 0.0.0.0 across every node. Surfaces internet-exposed services so /// the operator can see the attack surface at a glance. pub async fn fleet_security_listening_ports( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let local = move || collect_listening_ports(); let results = fleet_fanout_get::( &state, "/api/security/listening-ports-local", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// GET /api/security/listening-ports-local — node-local listener /// snapshot. Called by the coordinator via fleet-fanout. Auth: either /// session or cluster secret. pub async fn security_listening_ports_local( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(collect_listening_ports()) } /// Parse `ss -tlnp` output into a structured per-port view. Filters to /// listeners on `0.0.0.0` and `::` (publicly-exposed), groups by port, /// and notes the owning process. Returns an empty list if `ss` isn't /// available. fn collect_listening_ports() -> serde_json::Value { let out = std::process::Command::new("ss") .args(["-tlnp4", "-tlnp6"]) .output(); let stdout = match out { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(), _ => return serde_json::json!({ "ports": [], "error": "ss unavailable" }), }; let mut ports: Vec = Vec::new(); for line in stdout.lines() { if !line.starts_with("LISTEN") { continue; } let cols: Vec<&str> = line.split_whitespace().collect(); if cols.len() < 5 { continue; } let local_addr = cols[3]; // Only public listeners — 0.0.0.0:* or [::]:* let public = local_addr.starts_with("0.0.0.0:") || local_addr.starts_with("*:") || local_addr.starts_with("[::]:"); if !public { continue; } let port = local_addr.rsplit(':').next().unwrap_or("?"); // The process column wraps; collect everything after column 4 // and parse the "users:((..." segment. let proc_col = cols[5..].join(" "); let process = proc_col .find("\"") .and_then(|s| proc_col[s + 1..].find("\"").map(|e| &proc_col[s + 1..s + 1 + e])) .unwrap_or("?") .to_string(); ports.push(serde_json::json!({ "port": port, "local_addr": local_addr, "process": process, })); } serde_json::json!({ "ports": ports }) } /// POST /api/fleet/security/push-lockout-policy — write the same /// lockout config to every WolfStack node. Operator sets the policy /// once in the UI, we propagate it to all 14. pub async fn fleet_security_push_lockout_policy( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = body.into_inner(); // Apply locally first. if let Err(e) = state.login_limiter.set_config(cfg.clone()) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } // Fan out to peers. let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned() .collect(); (self_id, peers) }; let _ = self_id; let secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut node_results: Vec = Vec::new(); { for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/security/auth-config"); let mut ok = false; let mut err = String::new(); for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&secret) .json(&cfg) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; ok = true; break; } Ok(resp) => { let status = resp.status(); drain_response(resp).await; err = format!("HTTP {}", status); } Err(e) => { err = format!("transport: {}", e); } } } node_results.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "ok": ok, "error": if ok { String::new() } else { err }, })); } } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "self_applied": true, "peers": node_results, })) } /// POST /api/fleet/security/force-logout-all — invalidate every active /// session on every WolfStack node. Use this when you suspect session /// cookie theft. Operator must re-login everywhere after. pub async fn fleet_security_force_logout_all( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Local destroy: blow away every session in the SessionManager. state.sessions.destroy_all(); // Fan out. let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned() .collect(); (self_id, peers) }; let _ = self_id; let secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut succeeded = 1usize; // self let mut failed = 0usize; { for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/security/sessions-destroy-all"); let mut ok = false; for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .send().await; if let Ok(resp) = r { let success = resp.status().is_success(); drain_response(resp).await; if success { ok = true; break; } } } if ok { succeeded += 1; } else { failed += 1; } } } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "summary": format!("Destroyed all sessions on {} node(s); {} failed", succeeded, failed), })) } // ════════════════════════════════════════════════════════════════════ // Fleet-wide cluster-secret rotation // ════════════════════════════════════════════════════════════════════ // // The cluster secret is the inter-node auth token. If it leaks (via // the same path that leaked the root password) every WolfStack-to- // WolfStack call from anywhere on the internet can impersonate a // peer. This endpoint generates a new secret, distributes it to every // peer using the OLD secret (last-time use), each peer writes the new // value to disk, and returns success. The new secret takes effect // after the next WolfStack restart on each node — until then the old // is still active. // // Operator must restart WolfStack on every node to fully cut over. // We surface that explicitly in the response so they don't think it's // already live. #[derive(Deserialize)] pub struct RotateClusterSecretReceiveRequest { pub new_secret: String, } /// POST /api/security/cluster-secret/receive — peer-callable. Saves /// the new secret to /etc/wolfstack/cluster-secret. Authenticated via /// X-WolfStack-Secret using the CURRENT (old) secret — that's the /// last legitimate use of the old secret before it's superseded. /// /// Stage 5 fix: pre-Stage-5 this endpoint accepted ONLY the hardcoded /// default secret, which meant the matching coordinator /// (`fleet_security_rotate_cluster_secret`) only worked on installs /// that had never rotated. Now uses the shared three-way validator so /// the legacy rotation flow works on already-rotated installs too. The /// helper honours the Stage 5 env flag — operators who set /// WOLFSTACK_REJECT_DEFAULT_SECRET=1 still get the tighter check here. pub async fn security_cluster_secret_receive( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let presented = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !crate::auth::validate_inter_node_secret_from(presented, &state.cluster_secret, peer_ip(&req)) { return HttpResponse::Unauthorized().json(serde_json::json!({ "error": "invalid cluster secret", })); } let new = body.into_inner().new_secret; // Sanity-check format: must start with wsk_ and be reasonable length. if !new.starts_with("wsk_") || new.len() < 16 || new.len() > 256 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "new secret must start with 'wsk_' and be 16-256 chars", })); } // ORDERING: capture OLD on-disk secret before the save so we can // re-key this node's own at-rest stores from old→new. let old_secret = crate::auth::load_cluster_secret(); if let Err(e) = crate::auth::save_cluster_secret(&new) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e, })); } // Re-key local at-rest secrets (no-op if unchanged). The secret is // the at-rest encryption key — without this the node's local SQL / // OIDC / integration / DNS / cloud / XO credentials would be // undecryptable after its restart. let reencrypt = { let old = old_secret.clone(); let new2 = new.clone(); web::block(move || crate::secret_rotation::reencrypt_all_at_rest(&old, &new2)) .await.ok() }; // W2 fix: use the actual configured path in the response — pre-fix // hardcoded "/etc/wolfstack/cluster-secret" misled operators on // installs with paths.json overrides. let active_path = crate::paths::get().cluster_secret; HttpResponse::Ok().json(serde_json::json!({ "ok": true, "applied_at_restart": true, "at_rest_reencrypt": reencrypt, "note": format!("Secret written to {}. Restart WolfStack to activate.", active_path), })) } /// POST /api/fleet/security/rotate-cluster-secret — coordinator /// endpoint. Generates a new secret, fans out to every peer, returns /// per-peer status + the new secret value (so the operator can save /// it — though it's also persisted on every node). pub async fn fleet_security_rotate_cluster_secret( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // ORDERING: capture OLD on-disk secret before generating + saving the // new one, so we can re-key local at-rest stores from old→new. let old_secret = crate::auth::load_cluster_secret(); let new_secret = crate::auth::generate_cluster_secret(); // Apply locally first. if let Err(e) = crate::auth::save_cluster_secret(&new_secret) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("local save failed: {}", e), })); } // Re-key local at-rest secrets (no-op if old == new). let reencrypt = { let old = old_secret.clone(); let new = new_secret.clone(); web::block(move || crate::secret_rotation::reencrypt_all_at_rest(&old, &new)) .await.ok() }; // Fan out to every WolfStack peer using the CURRENT (old) secret. // If the old secret has already been compromised AND used to // change the secret elsewhere, this fanout would fail — operator // would see partial success and need to rotate manually. let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned() .collect(); (self_id, peers) }; let _ = self_id; // Auth the fanout with the IN-MEMORY current secret (the value // peers were started with). Pre-fix this used // `default_cluster_secret()` which only worked on the first // rotation of a never-rotated install — every subsequent rotation // failed all peer pushes because they no longer accepted the // hardcoded default. `state.cluster_secret` is the value loaded // at startup, which IS what each peer currently accepts. let old_secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut peer_results: Vec = Vec::new(); for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/security/cluster-secret/receive"); let body = serde_json::json!({ "new_secret": new_secret }); let mut ok = false; let mut err = String::new(); for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&old_secret) .json(&body) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; ok = true; break; } Ok(resp) => { let status = resp.status(); drain_response(resp).await; err = format!("HTTP {}", status); } Err(e) => { err = format!("transport: {}", e); } } } peer_results.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "ok": ok, "error": if ok { String::new() } else { err }, })); } let success_count = peer_results.iter().filter(|r| r["ok"].as_bool() == Some(true)).count(); let fail_count = peer_results.len() - success_count; HttpResponse::Ok().json(serde_json::json!({ "ok": fail_count == 0, "new_secret": new_secret, "self_applied": true, "at_rest_reencrypt": reencrypt, "peers": peer_results, "summary": format!( "Local + {}/{} peer(s) saved the new secret. {} failed. \ RESTART WOLFSTACK ON EVERY NODE to activate the new secret. \ Until restart, the OLD secret is still in use.", success_count, peer_results.len(), fail_count, ), "important": "Save the new secret value from this response if you want to keep a copy outside the fleet. WolfStack also persists it to /etc/wolfstack/cluster-secret on every node.", })) } // ════════════════════════════════════════════════════════════════════ // SSH hardening — fleet-wide push of safe sshd config // ════════════════════════════════════════════════════════════════════ // // Writes /etc/ssh/sshd_config.d/00-wolfstack-hardening.conf with the // settings the operator chose (PasswordAuthentication, PermitRootLogin, // PubkeyAuthentication). Verifies via `sshd -t` BEFORE reloading; if // the config is invalid we restore the backup and refuse the change // rather than risk a broken sshd that locks the operator out. // // **CRITICAL SAFETY GUARD**: We refuse to push a config that would // make the operator unable to log back in. Specifically: if the host // has NO authorized_keys for any user with a usable shell, we refuse // to set PasswordAuthentication=no — that would lock everyone out // permanently. Operator must either add a key first or override the // safety with `force=true`. #[derive(Deserialize, Serialize, Clone)] pub struct SshHardeningConfig { /// Set to "no", "yes", or "prohibit-password". Default: prohibit-password. #[serde(default = "default_permit_root")] pub permit_root_login: String, /// "yes" or "no". Default: no. #[serde(default = "default_password_auth")] pub password_authentication: String, /// "yes" or "no". Default: yes (force key-only). #[serde(default = "default_pubkey_auth")] pub pubkey_authentication: String, /// Bypass the "would lock you out" safety check. Use ONLY when you /// know what you're doing. #[serde(default)] pub force: bool, } fn default_permit_root() -> String { "prohibit-password".into() } fn default_password_auth() -> String { "no".into() } fn default_pubkey_auth() -> String { "yes".into() } const SSH_HARDENING_PATH: &str = "/etc/ssh/sshd_config.d/00-wolfstack-hardening.conf"; /// POST /api/security/ssh-hardening-local — apply hardening to THIS /// node. Validates with `sshd -t`, refuses if the change would lock /// the operator out (no authorized_keys + disabling password auth). pub async fn security_ssh_hardening_local( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = body.into_inner(); // Safety: refuse to disable password auth if there are no SSH keys // for any user with a real shell. This is the lock-out guard. if cfg.password_authentication == "no" && !cfg.force && !any_authorized_keys_present() { return HttpResponse::Conflict().json(serde_json::json!({ "ok": false, "error": "REFUSED: disabling password authentication when no authorized_keys files exist would permanently lock you out. Add an SSH key first OR pass force=true.", })); } let snippet = format!( "# Auto-generated by WolfStack — fleet SSH hardening.\n\ # Edit via Settings → Security → SSH hardening, NOT here.\n\ PermitRootLogin {}\n\ PasswordAuthentication {}\n\ PubkeyAuthentication {}\n\ ChallengeResponseAuthentication no\n\ KbdInteractiveAuthentication no\n\ UsePAM yes\n\ MaxAuthTries 3\n", sanitize_yes_no_or_prohibit(&cfg.permit_root_login, "prohibit-password"), sanitize_yes_no(&cfg.password_authentication, "no"), sanitize_yes_no(&cfg.pubkey_authentication, "yes"), ); // Backup any existing snippet for rollback. let backup = std::fs::read_to_string(SSH_HARDENING_PATH).ok(); if let Err(e) = std::fs::write(SSH_HARDENING_PATH, &snippet) { return HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": format!("write {}: {}", SSH_HARDENING_PATH, e), })); } // Validate. If `sshd -t` rejects the merged config, restore the // backup (or delete the file) and report the error. let validate = std::process::Command::new("sshd").arg("-t").output(); let valid = matches!(validate.as_ref(), Ok(o) if o.status.success()); if !valid { let stderr = validate .map(|o| String::from_utf8_lossy(&o.stderr).trim().to_string()) .unwrap_or_else(|e| format!("sshd spawn: {}", e)); match backup { Some(b) => { let _ = std::fs::write(SSH_HARDENING_PATH, b); } None => { let _ = std::fs::remove_file(SSH_HARDENING_PATH); } } return HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": format!("sshd -t rejected the new config; rolled back. Error: {}", stderr), })); } // Reload sshd. SIGHUP keeps existing sessions alive, picks up the // new config for new connections. let reload = std::process::Command::new("systemctl") .args(["reload", "ssh"]) .output(); let reload_ok = matches!(reload.as_ref(), Ok(o) if o.status.success()); if !reload_ok { // Try the other unit name (Debian uses `ssh`, RHEL uses `sshd`). let _ = std::process::Command::new("systemctl") .args(["reload", "sshd"]) .output(); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "applied": cfg, "config_path": SSH_HARDENING_PATH, })) } fn sanitize_yes_no(v: &str, fallback: &str) -> String { match v.trim().to_lowercase().as_str() { "yes" => "yes".into(), "no" => "no".into(), _ => fallback.into(), } } fn sanitize_yes_no_or_prohibit(v: &str, fallback: &str) -> String { match v.trim().to_lowercase().as_str() { "yes" => "yes".into(), "no" => "no".into(), "prohibit-password" | "without-password" => "prohibit-password".into(), _ => fallback.into(), } } /// True iff at least one user with a real shell has a non-empty /// authorized_keys file. Used by the SSH-hardening lock-out guard. fn any_authorized_keys_present() -> bool { authorized_keys_present_from( std::fs::File::open("/etc/passwd").map(std::io::BufReader::new), |path| std::fs::metadata(path).is_ok_and(|meta| meta.len() > 0), ) } fn authorized_keys_present_from( passwd: std::io::Result, mut has_keys: impl FnMut(&str) -> bool, ) -> bool { let passwd = match passwd { Ok(reader) => reader, Err(_) => return true, // can't tell — preserve the existing open-failure policy }; for line in passwd.lines() { let line = match line { Ok(line) => line, // The invalid line was consumed; valid users can still follow it. Err(error) if error.kind() == std::io::ErrorKind::InvalidData => continue, Err(_) => break, }; let parts: Vec<&str> = line.split(':').collect(); if parts.len() < 7 { continue; } let home = parts[5]; let shell = parts[6]; if !shell.ends_with("sh") { continue; } // skip nologin / false if has_keys(&format!("{}/.ssh/authorized_keys", home)) { return true; } } // Check /root specifically (might not be in /etc/passwd loop above). has_keys("/root/.ssh/authorized_keys") } /// POST /api/fleet/security/ssh-hardening — push the same SSH /// hardening config to every WolfStack peer. Each peer applies + /// validates locally; the response is per-peer success/failure. pub async fn fleet_security_ssh_hardening( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = body.into_inner(); // Apply locally first — if our own config is rejected, abort // before touching peers. We invoke security_ssh_hardening_local's // logic directly via a synthesised request would be ugly; instead // we duplicate the small core: write file + sshd -t. // Simplest: serialise the config and POST to ourselves on loopback. // Cleaner: extract a helper. Going with the helper. if let Err(e) = apply_ssh_hardening_local_inline(&cfg) { return HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": format!("local: {}", e), })); } let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned() .collect(); (self_id, peers) }; let _ = self_id; let secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut peer_results: Vec = Vec::new(); for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/security/ssh-hardening-local"); let mut ok = false; let mut err = String::new(); for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(15)) .peer_auth(&secret) .json(&cfg) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; ok = true; break; } Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); err = format!("HTTP {}: {}", status, body); } Err(e) => { err = format!("transport: {}", e); } } } peer_results.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "ok": ok, "error": if ok { String::new() } else { err }, })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "self_applied": true, "peers": peer_results, "applied_config": cfg, })) } /// Inline copy of the core SSH-hardening logic (write file + sshd -t /// + reload). Used by both the local endpoint and the fleet endpoint /// to apply locally without an HTTP round-trip to ourselves. fn apply_ssh_hardening_local_inline(cfg: &SshHardeningConfig) -> Result<(), String> { if cfg.password_authentication == "no" && !cfg.force && !any_authorized_keys_present() { return Err("REFUSED: disabling password auth with no SSH keys present would lock you out (pass force=true to override)".into()); } let snippet = format!( "# Auto-generated by WolfStack — fleet SSH hardening.\n\ # Edit via Settings → Security → SSH hardening, NOT here.\n\ PermitRootLogin {}\n\ PasswordAuthentication {}\n\ PubkeyAuthentication {}\n\ ChallengeResponseAuthentication no\n\ KbdInteractiveAuthentication no\n\ UsePAM yes\n\ MaxAuthTries 3\n", sanitize_yes_no_or_prohibit(&cfg.permit_root_login, "prohibit-password"), sanitize_yes_no(&cfg.password_authentication, "no"), sanitize_yes_no(&cfg.pubkey_authentication, "yes"), ); let backup = std::fs::read_to_string(SSH_HARDENING_PATH).ok(); std::fs::write(SSH_HARDENING_PATH, &snippet) .map_err(|e| format!("write {}: {}", SSH_HARDENING_PATH, e))?; let validate = std::process::Command::new("sshd").arg("-t").output(); if !matches!(validate.as_ref(), Ok(o) if o.status.success()) { let stderr = validate .map(|o| String::from_utf8_lossy(&o.stderr).trim().to_string()) .unwrap_or_else(|e| format!("sshd spawn: {}", e)); match backup { Some(b) => { let _ = std::fs::write(SSH_HARDENING_PATH, b); } None => { let _ = std::fs::remove_file(SSH_HARDENING_PATH); } } return Err(format!("sshd -t rejected config (rolled back): {}", stderr)); } let _ = std::process::Command::new("systemctl").args(["reload", "ssh"]).output(); let _ = std::process::Command::new("systemctl").args(["reload", "sshd"]).output(); Ok(()) } // ════════════════════════════════════════════════════════════════════ // Outbound-scan detector — config + events API // ════════════════════════════════════════════════════════════════════ /// GET /api/security/scan-detector — current config + recent events. pub async fn security_scan_detector_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(serde_json::json!({ "config": state.scan_detector.config(), "events": state.scan_detector.events(), })) } /// POST /api/security/scan-detector — update detector config. pub async fn security_scan_detector_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match state.scan_detector.set_config(body.into_inner()) { Ok(saved) => HttpResponse::Ok().json(saved), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/fleet/security/scan-detector — fleet-wide aggregated view. pub async fn fleet_security_scan_detector( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let det = state.scan_detector.clone(); let local = move || serde_json::json!({ "config": det.config(), "events": det.events(), }); let results = fleet_fanout_get::( &state, "/api/security/scan-detector", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// POST /api/fleet/security/push-scan-detector — push the same /// detector config to every WolfStack node. pub async fn fleet_security_push_scan_detector( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = body.into_inner(); if let Err(e) = state.scan_detector.set_config(cfg.clone()) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("local apply: {}", e), })); } let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned().collect(); (self_id, peers) }; let _ = self_id; let secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut peer_results = Vec::new(); { for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/security/scan-detector"); let mut ok = false; let mut err = String::new(); for url in &urls { let r = client.post(url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&secret) .json(&cfg) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; ok = true; break; } Ok(resp) => { let status = resp.status(); drain_response(resp).await; err = format!("HTTP {}", status); } Err(e) => { err = format!("transport: {}", e); } } } peer_results.push(serde_json::json!({ "hostname": node.hostname, "address": node.address, "ok": ok, "error": if ok { String::new() } else { err }, })); } } // Honest reporting: the local node always applied (we early-returned on // local failure above), but a security control silently not reaching some // peers is dangerous — a "push to every node" that skips unreachable // production nodes must NOT read as fully applied. Report per-node counts // and set the top-level `ok` false when any peer failed, so both API // consumers and the UI can surface the partial result. let peers_total = peer_results.len(); let peers_ok = peer_results.iter().filter(|p| p["ok"] == serde_json::json!(true)).count(); let peers_failed = peers_total - peers_ok; HttpResponse::Ok().json(serde_json::json!({ "ok": peers_failed == 0, "self_applied": true, "peers_total": peers_total, "peers_ok": peers_ok, "peers_failed": peers_failed, "peers": peer_results, })) } /// GET /api/security/host-audit — node-local container/VM/host audit. /// Heavy: spawns lots of subprocesses (lxc-ls, pct, docker, qm, virsh, /// find, ps, sshd -T, crontab). Run on a blocking task to keep the /// async runtime responsive. pub async fn security_host_audit( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let audit = tokio::task::spawn_blocking(crate::security_audit::collect_host_audit).await; match audit { Ok(a) => HttpResponse::Ok().json(a), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("audit task panicked: {}", e), })), } } /// GET /api/fleet/security/host-audit — fan out collect_host_audit() /// to every WolfStack-managed peer and aggregate. pub async fn fleet_security_host_audit( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let local = move || crate::security_audit::collect_host_audit(); let results = fleet_fanout_get::( &state, "/api/security/host-audit", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } // ════════════════════════════════════════════════════════════════════ // Antivirus / rootkit scanning — ClamAV + rkhunter + chkrootkit // Fleet-wide install/scan/quarantine. See src/antivirus/mod.rs. // ════════════════════════════════════════════════════════════════════ /// How long a fan-out POST waits per node. Fleet installs shell out /// to `apt-get` and legitimately take minutes; an authorised-key edit /// is a file write, and making the operator stare at a spinner for /// five minutes because one node is unreachable is its own bug. pub const FANOUT_SLOW: std::time::Duration = std::time::Duration::from_secs(300); pub const FANOUT_QUICK: std::time::Duration = std::time::Duration::from_secs(15); /// Fan a POST out to WolfStack peers in the cluster. Mirrors /// `fleet_fanout_get` but uses POST + JSON body. /// /// * `targets` — empty means every node; otherwise only the listed /// node ids, and nodes outside the list are omitted entirely rather /// than reported as skipped (they were never asked to act). /// * `local` — this node's ALREADY-COMPUTED result, or None when self /// isn't targeted. Passing the value rather than a closure lets /// callers whose local work blocks (filesystem, subprocesses) /// compute it on `spawn_blocking` first, off the async executor. /// * `timeout` — see `FANOUT_SLOW` / `FANOUT_QUICK`. async fn fleet_fanout_post( state: &web::Data, path: &str, body: serde_json::Value, targets: &[String], local: Option>, timeout: std::time::Duration, ) -> Vec> where Resp: serde::de::DeserializeOwned + Serialize + Send + 'static, { let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values().cloned().collect(); (self_id, peers) }; let secret = state.cluster_secret.clone(); let local_result = std::sync::Mutex::new(local); let mut tasks = Vec::new(); for node in peers { if !targets.is_empty() && !targets.contains(&node.id) { continue; } let is_self = node.id == self_id; let secret_c = secret.clone(); let path = path.to_string(); let body_c = body.clone(); let local_ref = if is_self { let mut g = local_result.lock().unwrap(); g.take() } else { None }; tasks.push(async move { if is_self { return match local_ref { Some(Ok(data)) => FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "ok".into(), data: Some(data), error: None, }, Some(Err(e)) => FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "failed".into(), data: None, error: Some(e), }, // Only reachable if self appears twice in the node // map — surface it rather than silently reporting ok. None => FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "failed".into(), data: None, error: Some("local result already consumed (duplicate self node?)".into()), }, }; } if node.node_type != "wolfstack" { return FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "skipped".into(), data: None, error: Some("non-WolfStack node".into()), }; } let urls = build_node_urls(&node.address, node.port, &path); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut errors: Vec = Vec::new(); for url in &urls { let resp = client.post(url) .timeout(timeout) .peer_auth(&secret_c) .json(&body_c) .send().await; match resp { Ok(r) if r.status().is_success() => { match r.json::().await { Ok(v) => return FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "ok".into(), data: Some(v), error: None, }, Err(e) => errors.push(format!("{} -> 200 OK but JSON parse failed: {}", url, e)), } } Ok(r) => { let status = r.status(); let body = r.text().await.unwrap_or_default(); // The remote's own message is the useful part // (e.g. a considered refusal), so lift it out of // the JSON envelope when there is one. let detail = serde_json::from_str::(&body) .ok() .and_then(|j| j.get("error").and_then(|v| v.as_str()).map(|s| s.to_string())) .unwrap_or_else(|| body.chars().take(300).collect()); errors.push(format!("{} -> HTTP {}: {}", url, status, detail)); } Err(e) => errors.push(format!("{} -> transport: {}", url, e)), } } FleetNodeResult { node_id: node.id, hostname: node.hostname, address: node.address, status: "failed".into(), data: None, error: Some(errors.join(" | ")), } }); } futures::future::join_all(tasks).await } #[derive(Serialize)] struct AntivirusStatusView { install: crate::antivirus::InstallStatus, scan: crate::antivirus::ScanState, config: crate::antivirus::AntivirusConfig, finding_count: usize, quarantine_count: usize, /// Newest finding timestamp seen on this node (RFC3339), or None. last_finding_at: Option, } fn build_antivirus_status_view(state: &AppState) -> AntivirusStatusView { state.antivirus.refresh_install_status(); let install = state.antivirus.install_status.read().unwrap().clone(); let scan = state.antivirus.scan_state.read().unwrap().clone(); let config = state.antivirus.config.read().unwrap().clone(); let findings = state.antivirus.findings.read().unwrap(); let finding_count = findings.len(); let last_finding_at = findings.first().map(|f| f.detected_at.clone()); let quarantine_count = state.antivirus.quarantine.read().unwrap().len(); AntivirusStatusView { install, scan, config, finding_count, quarantine_count, last_finding_at, } } /// GET /api/antivirus/status — installed tools, scan progress, counts. pub async fn antivirus_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(build_antivirus_status_view(&state)) } /// POST /api/antivirus/install — start an install in the background. /// Returns 202 immediately so the UI can open a terminal modal and /// poll `/api/antivirus/install-log` for live output as apt-get / dnf / /// pacman / zypper run. 409 if an install is already in progress on /// this node. pub async fn antivirus_install( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } { let g = state.antivirus.install_progress.read().unwrap(); if g.running { return HttpResponse::Conflict().json(serde_json::json!({ "error": "install already in progress on this node", "started_at": g.started_at, })); } } let av = state.antivirus.clone(); std::thread::spawn(move || { let _ = crate::antivirus::install_tools(&av); av.refresh_install_status(); }); HttpResponse::Accepted().json(serde_json::json!({ "ok": true, "message": "install started; poll /api/antivirus/install-log for progress", })) } /// GET /api/antivirus/install-log — live install progress + output. /// The UI polls this every ~1s while an install is running to populate /// a terminal-style log box. pub async fn antivirus_install_log( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let p = state.antivirus.install_progress.read().unwrap().clone(); HttpResponse::Ok().json(p) } #[derive(Deserialize)] pub struct OnAccessToggleBody { pub enabled: bool } /// POST /api/antivirus/on-access — toggle real-time on-access scanning. /// Returns 202 immediately; the apply runs in a background thread, /// streaming output to the same install_progress buffer the UI's /// terminal modal polls. 409 if an install/apply is already running. pub async fn antivirus_on_access( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } { let g = state.antivirus.install_progress.read().unwrap(); if g.running { return HttpResponse::Conflict().json(serde_json::json!({ "error": "an install/apply is already running on this node", "started_at": g.started_at, })); } } let target = body.enabled; let av = state.antivirus.clone(); // Persist the user's choice in config so it survives restart and // the status endpoint reflects intent. Actual systemd state is // refreshed separately. { let mut g = av.config.write().unwrap(); g.enable_on_access = target; let _ = g.save(); } std::thread::spawn(move || { crate::antivirus::apply_on_access(av.clone(), target); av.refresh_install_status(); }); HttpResponse::Accepted().json(serde_json::json!({ "ok": true, "target": target, "message": "on-access apply started; poll /api/antivirus/install-log for progress", })) } /// POST /api/antivirus/clamav/repair — run the ClamAV signature-DB /// repair flow (ensure clamav user, run freshclam, verify DB). /// Synchronous because the work is short (seconds, not minutes) and /// the operator wants to see the result immediately. piranhaSponsor's /// case (2026-05-27): scheduled-scan auto-recovery silently failed and /// the operator had no in-UI way to invoke the heal manually or see /// WHY it kept failing. pub async fn antivirus_clamav_repair( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Repair shells out to systemctl + freshclam; offload off the // tokio executor so we don't block the runtime on the (typically // 5-30 second) freshclam network fetch. let result = web::block(crate::antivirus::repair_clamav_signatures) .await .map_err(|e| format!("repair thread join failed: {}", e)); match result { Ok(r) => HttpResponse::Ok().json(serde_json::json!({ "ok": r.signatures_present_after, "signatures_present_after": r.signatures_present_after, "freshclam_ok": r.freshclam_ok, "healed_user": r.healed_user, "lines": r.lines, "error": r.error, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "ok": false, "error": e, })), } } /// POST /api/antivirus/scan — fire a full scan in a background thread. /// Returns immediately with 202 + the scan state so the UI can poll /// /api/antivirus/status for progress. pub async fn antivirus_scan_start( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Refuse to start a new scan if one is already running on this // node — keeps the "did I press the button twice?" race from // double-spawning clamscan (which would thrash the disk + double // the freshclam DB load). { let s = state.antivirus.scan_state.read().unwrap(); if s.running { return HttpResponse::Conflict().json(serde_json::json!({ "error": "scan already in progress on this node", "started_at": s.started_at, "active_scanner": s.active_scanner, })); } } let av = state.antivirus.clone(); std::thread::spawn(move || { let _ = crate::antivirus::run_full_scan(&av); }); HttpResponse::Accepted().json(serde_json::json!({ "ok": true, "message": "scan started; poll /api/antivirus/status for progress", })) } /// GET /api/antivirus/config — current configuration. pub async fn antivirus_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let cfg = state.antivirus.config.read().unwrap().clone(); HttpResponse::Ok().json(cfg) } /// PUT /api/antivirus/config — replace configuration. pub async fn antivirus_config_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mut cfg = body.into_inner(); // Clamp schedule to a sane range. if cfg.schedule_hours != 0 { cfg.schedule_hours = cfg.schedule_hours.clamp(1, 168); } { let mut g = state.antivirus.config.write().unwrap(); // On-access scanning is per-node state owned by POST // /api/antivirus/on-access. The settings form doesn't carry it, so a // plain replace reset it to false on every save while clamonacc kept // running — and the findings tailer then never resumed after restart. cfg.enable_on_access = g.enable_on_access; *g = cfg.clone(); } if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("save failed: {}", e), })); } HttpResponse::Ok().json(cfg) } /// GET /api/antivirus/findings — recent findings, newest first. pub async fn antivirus_findings( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let f = state.antivirus.findings.read().unwrap().clone(); HttpResponse::Ok().json(serde_json::json!({ "findings": f })) } /// GET /api/antivirus/quarantine — current quarantine inventory. pub async fn antivirus_quarantine_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let q = state.antivirus.quarantine.read().unwrap().clone(); HttpResponse::Ok().json(serde_json::json!({ "quarantine": q })) } #[derive(Deserialize)] pub struct QuarantineIdBody { pub id: String } /// POST /api/antivirus/quarantine/restore — restore a quarantined /// file to its original path with original mode + owner. pub async fn antivirus_quarantine_restore( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let av = state.antivirus.clone(); let id = body.id.clone(); let r = web::block(move || crate::antivirus::restore_quarantined(&av, &id)).await; match r { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("restore task panicked: {}", e), })), } } /// POST /api/antivirus/findings/dismiss — remove a finding from the /// list. Used to clear off rkhunter/chkrootkit alert-only findings /// the operator has reviewed and confirmed benign. Returns 404 if /// the id is unknown (already dismissed or never existed). Does NOT /// touch any quarantined file — only the in-memory + persisted /// findings table. pub async fn antivirus_findings_dismiss( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = match body.get("id").and_then(|v| v.as_str()) { Some(s) if !s.is_empty() => s.to_string(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "missing required field: id", })), }; let removed = crate::antivirus::dismiss_finding(&state.antivirus, &id); if removed { HttpResponse::Ok().json(serde_json::json!({ "ok": true, "dismissed": id })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": format!("no finding with id '{}' on this node", id), })) } } /// POST /api/antivirus/quarantine/delete — permanently delete a /// quarantined payload (shred if available, else unlink). pub async fn antivirus_quarantine_delete( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let av = state.antivirus.clone(); let id = body.id.clone(); let r = web::block(move || crate::antivirus::delete_quarantined(&av, &id)).await; match r { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("delete task panicked: {}", e), })), } } // ───────── Fleet aggregation ───────── /// GET /api/fleet/antivirus/status — aggregated per-node install + /// scan state across every WolfStack peer in the cluster. Also /// returns `self_id` so the UI can route per-node actions (restore, /// delete) to the local API for this node and node-proxy for peers. pub async fn fleet_antivirus_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let self_id = state.cluster.self_id.clone(); let state_for_local = state.clone(); let local = move || serde_json::to_value(build_antivirus_status_view(&state_for_local)) .unwrap_or(serde_json::Value::Null); let results = fleet_fanout_get::( &state, "/api/antivirus/status", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results, "self_id": self_id, })) } /// POST /api/fleet/antivirus/install — kick off install on every node /// in the cluster. Each per-node install is async (returns 202 /// immediately, runs in a background thread on that node, capturing /// log lines into /api/antivirus/install-log). The frontend drives the /// node-by-node sequence directly so it can render per-node terminal /// output as each install proceeds; this endpoint is the "fan all the /// triggers out at once" shortcut for unattended scripted runs. pub async fn fleet_antivirus_install( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let state_for_local = state.clone(); let local = move || { // Already-running short-circuit so a double-click doesn't // start two installs. let already_running = state_for_local.antivirus.install_progress.read() .map(|g| g.running).unwrap_or(false); if already_running { return serde_json::json!({ "ok": false, "skipped": "install already in progress" }); } let av = state_for_local.antivirus.clone(); std::thread::spawn(move || { let _ = crate::antivirus::install_tools(&av); av.refresh_install_status(); }); serde_json::json!({ "ok": true, "started": true }) }; let results = fleet_fanout_post::( &state, "/api/antivirus/install", serde_json::json!({}), &[], Some(Ok(local())), FANOUT_SLOW, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// POST /api/fleet/antivirus/scan — kick off a scan on every node. pub async fn fleet_antivirus_scan( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let state_for_local = state.clone(); let local = move || { // Mirror the per-node refusal: if a scan is running, return // a structured "skipped" rather than starting a second one. let already_running = state_for_local.antivirus.scan_state.read() .map(|s| s.running).unwrap_or(false); if already_running { return serde_json::json!({ "ok": false, "skipped": "scan already in progress" }); } let av = state_for_local.antivirus.clone(); std::thread::spawn(move || { let _ = crate::antivirus::run_full_scan(&av); }); serde_json::json!({ "ok": true, "started": true }) }; let results = fleet_fanout_post::( &state, "/api/antivirus/scan", serde_json::json!({}), &[], Some(Ok(local())), FANOUT_SLOW, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// GET /api/fleet/antivirus/findings — fleet-wide findings. pub async fn fleet_antivirus_findings( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let state_for_local = state.clone(); let local = move || { let f = state_for_local.antivirus.findings.read().unwrap().clone(); serde_json::json!({ "findings": f }) }; let results = fleet_fanout_get::( &state, "/api/antivirus/findings", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// POST /api/fleet/antivirus/push-config — apply config locally, then /// PUT it to every WolfStack peer in the cluster. Mirrors the /// `fleet_security_push_scan_detector` pattern: one click in the UI /// reaches every node with no per-node loop on the frontend. pub async fn fleet_antivirus_push_config( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mut cfg = body.into_inner(); if cfg.schedule_hours != 0 { cfg.schedule_hours = cfg.schedule_hours.clamp(1, 168); } // Apply locally. `enable_on_access` is per-node (see antivirus_config_set) // — keep ours here; each peer keeps its own in its PUT handler. The copy // sent to peers is left as received and ignored by them. let local_cfg = { let mut g = state.antivirus.config.write().unwrap(); let mut local = cfg.clone(); local.enable_on_access = g.enable_on_access; *g = local.clone(); local }; if let Err(e) = local_cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("local save: {}", e), })); } let (self_id, peers) = { let n = state.cluster.nodes_read(); let self_id = state.cluster.self_id.clone(); let peers: Vec = n.values() .filter(|p| p.id != self_id && p.node_type == "wolfstack") .cloned().collect(); (self_id, peers) }; let _ = self_id; let secret = state.cluster_secret.clone(); // Shared pooled inter-node client (identical TLS policy). let client = &*API_HTTP_CLIENT; let mut peer_results = Vec::new(); { for node in peers { let urls = build_node_urls(&node.address, node.port, "/api/antivirus/config"); let mut ok = false; let mut err = String::new(); for url in &urls { let r = client.put(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&secret) .json(&cfg) .send().await; match r { Ok(resp) if resp.status().is_success() => { drain_response(resp).await; ok = true; break; } Ok(resp) => { let status = resp.status(); drain_response(resp).await; err = format!("HTTP {}", status); } Err(e) => { err = format!("transport: {}", e); } } } peer_results.push(serde_json::json!({ "hostname": node.hostname, "address": node.address, "ok": ok, "error": if ok { String::new() } else { err }, })); } } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "self_applied": true, "peers": peer_results, })) } /// GET /api/fleet/antivirus/quarantine — fleet-wide quarantine inventory. pub async fn fleet_antivirus_quarantine( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let state_for_local = state.clone(); let local = move || { let q = state_for_local.antivirus.quarantine.read().unwrap().clone(); serde_json::json!({ "quarantine": q }) }; let results = fleet_fanout_get::( &state, "/api/antivirus/quarantine", local, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": results })) } /// POST /api/security/sessions-destroy-all — node-local session wipe. /// Cluster-secret only (called by the coordinator's force-logout). pub async fn security_sessions_destroy_all( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } state.sessions.destroy_all(); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } pub async fn vlan_discover(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let store = crate::networking::vlan::VlanStore::load(); let found = crate::networking::vlan::discover(&store); HttpResponse::Ok().json(serde_json::json!({ "discovered": found })) } /// POST /api/networking/vlan/preflight — run safety checks against the /// current store + an optional proposed VlanAttachment. Returns the /// findings so the UI can render disruption warnings before commit. /// Body is the proposed VlanAttachment (or empty `{}` for a global /// re-check of the saved store). pub async fn vlan_preflight( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let store = crate::networking::vlan::VlanStore::load(); let manager = crate::networking::vlan::detect_net_manager(); // Try to deserialize the body as a VlanAttachment. An empty body / // missing required fields just means "no proposal — check current state". let proposed: Option = serde_json::from_value(body.into_inner()).ok(); let findings = crate::networking::vlan::preflight(&store, manager, proposed.as_ref()); HttpResponse::Ok().json(serde_json::json!({ "manager": manager, "preflight": findings, })) } #[derive(Deserialize)] pub struct VlanAttachRequest { /// VLAN attachment id (vlan-XXXXX) on this node. pub vlan_id: String, pub target_kind: crate::networking::vlan::TargetKind, pub target_id: String, /// IP to allocate. Empty/missing = ask backend to pick next-available. #[serde(default)] pub ip: String, /// Operator-facing label. Optional. #[serde(default)] pub label: String, /// VM target kinds only: reboot the guest after staging cloud-init /// so the IP applies immediately. Ignored for containers/Docker /// (which restart as part of the attach) and Manual. #[serde(default)] pub reboot: bool, } /// POST /api/networking/vlan/attach — allocate an IP on a VLAN and /// run the backend-specific attach (write container config, restart, /// etc.). On failure, the IP is NOT recorded so a retry doesn't see /// a phantom allocation. pub async fn vlan_attach( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let mut store = crate::networking::vlan::VlanStore::load(); // Look up the VLAN. let vlan = match store.vlans.iter().find(|v| v.id == body.vlan_id) { Some(v) => v.clone(), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("vlan attachment '{}' not found", body.vlan_id), })), }; // Attaching through WolfStack assigns the guest a static IP, and both // auto-pick and the prefix length come from the VLAN's subnet. Without one // we would either report the misleading "no free IPs left" (auto-pick) or // silently guess /24 onto an operator-supplied address — refuse up front // instead. This is NOT the same as the host having no IP: self_ip may be // blank (L2-only host) as long as the guests' subnet is recorded. if vlan.subnet.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!( "VLAN '{}' has no subnet recorded, so WolfStack cannot assign guest IPs on it. \ Set the VLAN's subnet (this host's own IP can stay blank if it should remain \ off the VLAN), or attach nothing and configure addressing inside the guest by hand.", vlan.name, ), })); } // Pick the IP — operator-supplied or next-available. let ip = if body.ip.is_empty() { // Aggregate cluster-wide used IPs for this subnet first so we // don't conflict with allocations on other nodes. let cluster_used = aggregate_cluster_used_ips(&state, &vlan.subnet).await; match crate::networking::vlan::next_available_ip(&vlan, &cluster_used) { Some(ip) => ip, None => return HttpResponse::Conflict().json(serde_json::json!({ "error": "subnet has no free IPs left (after subtracting local + external + cluster allocations)", })), } } else { body.ip.clone() }; let cidr_prefix = vlan.subnet.split('/').nth(1).and_then(|s| s.parse::().ok()).unwrap_or(24); let ip_cidr = format!("{}/{}", ip, cidr_prefix); // On an L2-only VLAN the host takes no address, so there is no gateway to // hand the guest — `self_ip` is empty and must NOT be passed through as a // blank gateway (that would write `gateway ` into the guest's config, or // `--gateway ""` for Docker, and fail at apply time). let gateway = vlan.routes.first().map(|r| r.via.as_str()) .or(if !vlan.self_ip.is_empty() && vlan.self_ip != ip { Some(vlan.self_ip.as_str()) } else { None }); let params = crate::networking::vlan_attach::AttachParams { bridge: &vlan.bridge_name, ip_cidr: &ip_cidr, mtu: vlan.mtu, gateway, routes: &vlan.routes, reboot: body.reboot, target_id: &body.target_id, }; // Run the backend-specific attach. let outcome_result = match body.target_kind { crate::networking::vlan::TargetKind::LxcNative => crate::networking::vlan_attach::attach_lxc_native(¶ms), crate::networking::vlan::TargetKind::LxcProxmox => crate::networking::vlan_attach::attach_lxc_proxmox(¶ms), crate::networking::vlan::TargetKind::VmProxmox => crate::networking::vlan_attach::attach_vm_proxmox(¶ms), crate::networking::vlan::TargetKind::VmNative => crate::networking::vlan_attach::attach_vm_libvirt(¶ms), crate::networking::vlan::TargetKind::Docker => { // Hetzner vSwitch enforces 1 MAC per port — macvlan would // create a unique MAC per container and the vSwitch would // silently drop those packets. ipvlan L2 shares the parent's // MAC and works on Hetzner. For OVH/Equinix/Custom we use // macvlan (true L2 isolation between containers). let driver = match vlan.provider { crate::networking::vlan::VlanProvider::Hetzner => crate::networking::vlan_attach::DockerVlanDriver::IpvlanL2, _ => crate::networking::vlan_attach::DockerVlanDriver::Macvlan, }; // Docker macvlan/ipvlan attaches to the underlying L2 // device, NOT the bridge — pass the tagged sub-interface // (e.g. eno1.4000), which is how the kernel actually sees // the VLAN traffic. let parent = format!("{}.{}", vlan.parent_iface, vlan.vlan_id); crate::networking::vlan_attach::attach_docker( ¶ms, &parent, &vlan.subnet, &vlan.self_ip, driver, ) } crate::networking::vlan::TargetKind::Manual => { // Manual reservation — no backend to call. Ok(crate::networking::vlan_attach::AttachOutcome { message: format!("Reserved {} on {} (no backend attach — manual)", ip, vlan.bridge_name), restarted: false, }) } }; let outcome = match outcome_result { Ok(o) => o, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("backend attach failed: {}", e), })), }; // Backend succeeded — record the allocation. if let Err(e) = store.allocate_ip(&body.vlan_id, &ip, body.target_kind, &body.target_id, &body.label) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("backend attached but failed to record allocation: {}. Manual cleanup may be needed.", e), })); } if let Err(e) = store.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("backend attached but allocation save failed: {}", e), })); } HttpResponse::Ok().json(serde_json::json!({ "ip": ip, "ip_cidr": ip_cidr, "message": outcome.message, "restarted": outcome.restarted, })) } #[derive(Deserialize)] pub struct VlanDetachRequest { pub vlan_id: String, pub target_kind: crate::networking::vlan::TargetKind, pub target_id: String, /// IP being released. Required so we can deallocate the right slot /// when a target has multiple interfaces on the same VLAN. pub ip: String, } /// POST /api/networking/vlan/detach — reverse of attach. Always tries /// to release the IP from the local store even if the backend detach /// fails (so a half-cleaned-up state doesn't permanently leak the IP). pub async fn vlan_detach( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let mut store = crate::networking::vlan::VlanStore::load(); let vlan = match store.vlans.iter().find(|v| v.id == body.vlan_id) { Some(v) => v.clone(), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("vlan attachment '{}' not found", body.vlan_id), })), }; let backend_result = match body.target_kind { crate::networking::vlan::TargetKind::LxcNative => crate::networking::vlan_attach::detach_lxc_native(&body.target_id, &vlan.bridge_name), crate::networking::vlan::TargetKind::LxcProxmox => crate::networking::vlan_attach::detach_lxc_proxmox(&body.target_id, &vlan.bridge_name), crate::networking::vlan::TargetKind::VmProxmox => crate::networking::vlan_attach::detach_vm_proxmox(&body.target_id, &vlan.bridge_name), crate::networking::vlan::TargetKind::VmNative => crate::networking::vlan_attach::detach_vm_libvirt(&body.target_id, &vlan.bridge_name), crate::networking::vlan::TargetKind::Docker => crate::networking::vlan_attach::detach_docker(&body.target_id, &vlan.bridge_name), crate::networking::vlan::TargetKind::Manual => Ok(crate::networking::vlan_attach::AttachOutcome { message: format!("Released manual reservation {} on {}", body.ip, vlan.bridge_name), restarted: false, }), }; // Always release the local allocation even on backend failure. let removed = store.deallocate_ip(&body.vlan_id, &body.ip); let _ = store.save(); match backend_result { Ok(o) => HttpResponse::Ok().json(serde_json::json!({ "released": removed, "message": o.message, })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "released": removed, "warning": format!("local allocation released, but backend detach reported: {}", e), })), } } /// POST /api/networking/vlan/test/{vlan_id} — ping every IP that this /// server thinks is on the named VLAN's subnet (local allocations, /// peer allocations, external reservations, and the configured /// gateway). Returns reachable/unreachable per IP. Lets the operator /// verify a freshly-created vSwitch is actually working without /// dropping to a shell. pub async fn vlan_test( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let vlan_id = path.into_inner(); let store = crate::networking::vlan::VlanStore::load(); let vlan = match store.vlans.iter().find(|v| v.id == vlan_id) { Some(v) => v.clone(), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("vlan attachment '{}' not found", vlan_id), })), }; // Build the candidate list: local allocations, guests discovered live // on the bridge, gateway IPs from routes, and aggregated peer/external // IPs from cluster-used. let mut candidates: Vec<(String, String)> = Vec::new(); // (ip, label) for a in &vlan.allocations { let label = if a.label.is_empty() { a.target_id.clone() } else { a.label.clone() }; candidates.push((a.ip.clone(), format!("local: {}", label))); } // Guests wired to the bridge outside this page's attach flow — without // these, a bridge full of hand-attached LXCs "has nothing to test" // (RutgerDiehard, 2026-08-07). Discovery shells out; off the workers. let bridge_name = vlan.bridge_name.clone(); let discovered = web::block(move || crate::networking::vlan::discover_bridge_guests(&bridge_name)) .await .unwrap_or_default(); let mut unpingable_guests = 0usize; for g in &discovered { match &g.ip { Some(ip) => candidates.push((ip.clone(), format!("on bridge: {} ({})", g.name, g.kind))), None => unpingable_guests += 1, } } for r in &vlan.routes { candidates.push((r.via.clone(), format!("gateway for {}", r.destination))); } let peer_map = fetch_peer_ips_in_subnet(&state, &vlan.subnet).await; for (peer_id, ips) in peer_map { for ip in ips { // Skip our own self_ip - we don't ping ourselves. if ip == vlan.self_ip { continue; } candidates.push((ip, format!("peer {}", peer_id))); } } // Dedupe by IP, keep the first label seen. let mut seen: std::collections::HashSet = std::collections::HashSet::new(); candidates.retain(|(ip, _)| seen.insert(ip.clone())); if candidates.is_empty() { // Distinguish "the bridge really is empty" from "guests are there // but none has an address we can ping" (DHCP LXC, VMs that manage // their own IPs) — the blanket "nothing on this VLAN" reading is // what confused RutgerDiehard when his LXCs were right there. let summary = if unpingable_guests > 0 { format!( "Found {} guest{} on bridge {} but none with a known IP to ping — their addresses are DHCP or guest-managed. Add them via Attach (or a Reservation) to make them testable.", unpingable_guests, if unpingable_guests == 1 { "" } else { "s" }, vlan.bridge_name ) } else { "Nothing to test — no allocations, guests on the bridge, peers, or gateways known on this VLAN yet.".to_string() }; return HttpResponse::Ok().json(serde_json::json!({ "vlan_id": vlan_id, "results": [], "summary": summary, })); } // Run the pings in parallel via tokio::task::spawn_blocking so the // sequential 1-second timeouts don't add up. let mut futures = Vec::with_capacity(candidates.len()); for (ip, label) in candidates { futures.push(tokio::task::spawn_blocking(move || { let out = std::process::Command::new("ping") .args(["-c", "1", "-W", "1", "-n", &ip]) .output(); let reachable = matches!(out, Ok(o) if o.status.success()); serde_json::json!({ "ip": ip, "label": label, "reachable": reachable, }) })); } let mut results = Vec::with_capacity(futures.len()); for f in futures { match f.await { Ok(v) => results.push(v), Err(e) => results.push(serde_json::json!({ "ip": "?", "label": "ping task panicked", "reachable": false, "error": e.to_string(), })), } } let total = results.len(); let ok = results.iter().filter(|r| r.get("reachable").and_then(|v| v.as_bool()).unwrap_or(false)).count(); HttpResponse::Ok().json(serde_json::json!({ "vlan_id": vlan_id, "results": results, "summary": format!("{} of {} reachable", ok, total), })) } /// GET /api/networking/vlan/cluster-used?subnet=10.0.1.0/24 — return /// every IP currently in use on the named subnet across every node in /// THIS WolfStack admin cluster. The frontend uses this to render /// "X.Y.Z.W is taken (by NodeFoo)" hints when picking an IP manually. /// /// Cycle-breaker: when called via X-WolfStack-Secret (peer auth), we /// return ONLY the local node's allocations — no further fan-out. pub async fn vlan_cluster_used(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let from_peer = caller == "cluster-node"; let subnet = req.uri().query() .and_then(|q| { for pair in q.split('&') { if let Some(rest) = pair.strip_prefix("subnet=") { return urlencoding::decode(rest).ok().map(|s| s.into_owned()); } } None }) .unwrap_or_default(); if subnet.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "subnet query parameter is required", })); } let local_ips = local_ips_in_subnet(&subnet); if from_peer { // Peer call — return only local, don't re-aggregate. return HttpResponse::Ok().json(serde_json::json!({ "node_id": state.node_id.clone(), "ips": local_ips, })); } // Operator call — fan out to peers in parallel. let peer_ips = fetch_peer_ips_in_subnet(&state, &subnet).await; HttpResponse::Ok().json(serde_json::json!({ "subnet": subnet, "local_ips": local_ips, "peer_ips": peer_ips, })) } /// Helper: list the IPs allocated locally on the named subnet. fn local_ips_in_subnet(subnet: &str) -> Vec { let store = crate::networking::vlan::VlanStore::load(); let mut out: Vec = Vec::new(); for v in &store.vlans { if v.subnet != subnet { continue; } // Self IP counts. out.push(v.self_ip.clone()); // Allocations. for a in &v.allocations { out.push(a.ip.clone()); } // External reservations expanded. for r in &v.external_reservations { if let Some((lo, hi)) = r.spec.split_once('-') { if let (Ok(lo_ip), Ok(hi_ip)) = (lo.trim().parse::(), hi.trim().parse::()) { let l = u32::from(lo_ip); let h = u32::from(hi_ip); for n in l..=h { out.push(std::net::Ipv4Addr::from(n).to_string()); } } } else if r.spec.parse::().is_ok() { out.push(r.spec.trim().to_string()); } } } out } /// Fan out to every online wolfstack peer asking for its /// vlan/cluster-used local view, returning a map of peer-id to IP list. async fn fetch_peer_ips_in_subnet( state: &web::Data, subnet: &str, ) -> std::collections::HashMap> { let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let self_id = state.cluster.self_id.clone(); let peers: Vec<(String, String, u16)> = nodes.iter() .filter(|n| !n.is_self && n.id != self_id && n.online && n.node_type == "wolfstack") .map(|n| (n.id.clone(), n.address.clone(), n.port)) .collect(); if peers.is_empty() { return std::collections::HashMap::new(); } let client = &*API_HTTP_CLIENT; let path = format!("/api/networking/vlan/cluster-used?subnet={}", urlencoding::encode(subnet)); let mut futures = Vec::with_capacity(peers.len()); for (id, address, port) in peers { let secret = secret.clone(); let client = client.clone(); let path = path.clone(); futures.push(async move { let urls = build_node_urls(&address, port, &path); for url in &urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(4)) .peer_auth(&secret) .send() .await && resp.status().is_success() && let Ok(body) = resp.json::().await && let Some(arr) = body.get("ips").and_then(|v| v.as_array()) { let ips: Vec = arr.iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) .collect(); return Some((id, ips)); } } None }); } let results = futures::future::join_all(futures).await; let mut out: std::collections::HashMap> = std::collections::HashMap::new(); for r in results.into_iter().flatten() { out.insert(r.0, r.1); } out } /// Aggregate every used IP on the named subnet from local + peers. /// Used by the attach endpoint when picking next-available IP. async fn aggregate_cluster_used_ips( state: &web::Data, subnet: &str, ) -> Vec { let mut all = local_ips_in_subnet(subnet); let peer_map = fetch_peer_ips_in_subnet(state, subnet).await; for (_, ips) in peer_map { all.extend(ips); } all } // ─── Backup API ─── #[derive(Deserialize)] pub struct CreateBackupRequest { /// Optional specific target — if omitted, backup everything pub target: Option, pub storage: backup::BackupStorage, /// Cluster name override — sent by frontend so remote nodes use the correct cluster #[serde(default)] pub cluster_name: Option, } #[derive(Deserialize)] pub struct CreateScheduleRequest { /// Present when EDITING an existing schedule (Gary 2026-06-25) — the existing /// id is updated in place (created_at/last_run preserved). Absent = create new. #[serde(default)] pub id: Option, pub name: String, pub frequency: backup::BackupFrequency, pub time: String, pub retention: u32, pub backup_all: bool, #[serde(default)] pub targets: Vec, pub storage: backup::BackupStorage, #[serde(default = "default_true")] pub enabled: bool, /// Pre/post hook commands (wabil 2026-07-02). Default-empty so older /// frontends that don't send them keep working. #[serde(default)] pub pre_command: String, #[serde(default)] pub post_command: String, /// Where this schedule applies. Absent → `Node` → the exact behaviour every /// existing caller already gets, so old frontends are unaffected. `Fleet` /// writes it to every WolfStack node in the cluster and reports per node. #[serde(default)] pub scope: BackupScope, /// With `scope: fleet`, restrict the write to these node ids. Empty (the /// default) means every WolfStack node — which is what "fleet" means unless /// the operator narrowed it in the node picker. #[serde(default)] pub target_nodes: Vec, /// Weekly schedules: ISO weekday to run on (1 = Monday … 7 = Sunday). /// Absent → unpinned, the pre-existing "seven days since the last run" /// behaviour (JJ 2026-08-19). #[serde(default)] pub day_of_week: Option, /// Monthly schedules: day of the month to run on (1–31; a day the month /// doesn't have runs on its last day). Absent → unpinned. #[serde(default)] pub day_of_month: Option, /// `backup_all` schedules: take COLD container backups (stop each container /// for its archive). Absent → live backups, as before. #[serde(default)] pub stop_containers: bool, /// `backup_all` schedules: back running VMs up live instead of shutting /// them down. Absent → VMs are shut down for their backup, as before. #[serde(default)] pub keep_vms_running: bool, /// `backup_all` schedules: Docker containers mounts-only. Absent → full. #[serde(default)] pub docker_mounts_only: bool, } #[derive(Deserialize)] pub struct ToggleScheduleRequest { pub enabled: bool, } /// GET /api/backups — list all backup entries pub async fn backup_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(backup::list_backups).await { Ok(entries) => HttpResponse::Ok().json(backup_entries_for_api(entries)), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("backup list task: {}", e), })), } } /// Backup entries as returned by the API. Each entry carries a full /// copy of its `BackupStorage` (S3 secret key, PBS token secret / password, /// SMB password) and, for Docker targets, the raw `docker inspect` JSON in /// `docker_config` — whose `Config.Env` holds the container's environment /// (database passwords, API tokens). Both went out verbatim to every /// authenticated caller, viewer sessions and `read` API keys included. /// Restores look the entry up server-side by id, and nothing client-side /// reads `docker_config`, so it is dropped (empty → skipped on serialize) /// and the storage secrets are masked like the schedules endpoint does. fn backup_entries_for_api(entries: Vec) -> Vec { entries.into_iter().map(|mut e| { e.docker_config.clear(); crate::secrets::to_redacted_json(&e) }).collect() } /// POST /api/backups — create a backup now pub async fn backup_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mut storage = body.storage.clone(); // Validate the WolfDisk subpath at the API boundary so a // crafted POST can't silently pick a sanitized-but-different // path. The lenient resolver in resolved_local_path() strips // `..` segments defence-in-depth, but we want the operator to // get a clear 400 rather than a backup that ran to a different // directory than they asked for. if matches!(storage.storage_type, backup::StorageType::Wolfdisk) && let Err(e) = backup::BackupStorage::validate_wolfdisk_subpath(&storage.wolfdisk_subpath) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } // Validate a system-folder target's path up front (absolute, exists, not // a dangerous root) so the operator gets a clear 400 immediately. if let Some(t) = &body.target && t.target_type == backup::BackupTargetType::SystemPath && let Err(e) = backup::validate_system_path(&t.system_path) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } backup::merge_pbs_secrets(&mut storage); // W6 fix: backup::create_backup runs `qemu-img convert` for VM // disks — potentially many minutes for a multi-GB image. Wrap in // web::block so the actix worker isn't pinned for the duration. // The blocking pool exists exactly for this. let target_clone = body.target.clone(); let entries = match web::block(move || backup::create_backup(target_clone, storage)).await { Ok(e) => e, Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("backup task: {}", e), })); } }; let success_count = entries.iter().filter(|e| e.status == backup::BackupStatus::Completed).count(); let fail_count = entries.iter().filter(|e| e.status == backup::BackupStatus::Failed).count(); HttpResponse::Ok().json(serde_json::json!({ "message": format!("{} backup(s) completed, {} failed", success_count, fail_count), "entries": backup_entries_for_api(entries), })) } /// POST /api/backups/stream — run backup with SSE log output pub async fn backup_stream( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mut storage = body.storage.clone(); // Mirror backup_create's WolfDisk subpath validation. SSE-stream // path is the one most operators hit from the UI, so a 400 here // surfaces the error in the streaming console rather than letting // the run silently retarget a sanitized path. if matches!(storage.storage_type, backup::StorageType::Wolfdisk) && let Err(e) = backup::BackupStorage::validate_wolfdisk_subpath(&storage.wolfdisk_subpath) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } if let Some(t) = &body.target && t.target_type == backup::BackupTargetType::SystemPath && let Err(e) = backup::validate_system_path(&t.system_path) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } backup::merge_pbs_secrets(&mut storage); let target = body.target.clone(); let cluster_name = Some(body.cluster_name.clone() .unwrap_or_else(|| state.cluster.get_self_cluster_name())); // Use tokio mpsc so we can await recv() without blocking the runtime let (tx, mut rx) = tokio::sync::mpsc::channel::(256); // Bridge: backup code uses std::sync::mpsc, so we bridge to tokio channel let (std_tx, std_rx) = std::sync::mpsc::channel::(); // Spawn the backup in a blocking thread using std channel std::thread::spawn(move || { backup::create_backup_with_log(target, storage, std_tx, cluster_name); }); // Bridge thread: reads from std channel and forwards to tokio channel tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tx.blocking_send(msg).is_err() { break; } } }); // Stream SSE events from the tokio channel let stream = async_stream::stream! { loop { // Heartbeat: a restore can be silent for minutes (a large // `docker load`, a PBS pull), and an idle connection with no bytes // gets reaped — by the browser or, more often, a reverse proxy's // read timeout — which surfaces in the UI as a bare fetch failure // ("Load failed" / "Failed to fetch") with no server error. Emitting // an SSE comment every 15s keeps the socket warm. Comment lines // (`:`-prefixed) are ignored by the client's `data:` parser. match tokio::time::timeout(std::time::Duration::from_secs(15), rx.recv()).await { Ok(Some(msg)) => { let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } Ok(None) => break, // channel closed — restore thread finished Err(_) => { yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from_static(b": keepalive\n\n")); } } } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } /// POST /api/backups/{id}/restore/stream — restore with SSE progress pub async fn backup_restore_stream( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let overwrite = query.get("overwrite").map(|v| v == "true").unwrap_or(false); let storage = query.get("storage").cloned().unwrap_or_default(); let new_name = query.get("name").cloned().unwrap_or_default(); // Config restore only: "new machine" drops node identity / TLS / networking // so the backup can be carried onto a different box. Ignored for other types. let new_machine = query.get("new_machine").map(|v| v == "true").unwrap_or(false); // Check for container existence before streaming (to return 409 synchronously) { let config = backup::load_config(); if let Some(entry) = config.entries.iter().find(|e| e.id == id) && entry.target.target_type == backup::BackupTargetType::Docker && !overwrite { let check = std::process::Command::new("docker") .args(["container", "inspect", &entry.target.name]) .output(); if check.map(|o| o.status.success()).unwrap_or(false) { return HttpResponse::Conflict().json(serde_json::json!({ "error": "container_exists", "container": entry.target.name, "message": format!("Container '{}' already exists. Overwrite?", entry.target.name) })); } } } let (std_tx, std_rx) = std::sync::mpsc::channel::(); let (tx, mut rx) = tokio::sync::mpsc::channel::(256); std::thread::spawn(move || { let result = backup::restore_by_id_with_log(&id, overwrite, &storage, &new_name, new_machine, std_tx.clone()); match result { Ok(msg) => { let _ = std_tx.send(format!("RESULT:OK:{}", msg)); } Err(e) => { let _ = std_tx.send(format!("RESULT:ERR:{}", e)); } } }); tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tx.blocking_send(msg).is_err() { break; } } }); let stream = async_stream::stream! { loop { // Heartbeat: a restore can be silent for minutes (a large // `docker load`, a PBS pull), and an idle connection with no bytes // gets reaped — by the browser or, more often, a reverse proxy's // read timeout — which surfaces in the UI as a bare fetch failure // ("Load failed" / "Failed to fetch") with no server error. Emitting // an SSE comment every 15s keeps the socket warm. Comment lines // (`:`-prefixed) are ignored by the client's `data:` parser. match tokio::time::timeout(std::time::Duration::from_secs(15), rx.recv()).await { Ok(Some(msg)) => { let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } Ok(None) => break, // channel closed — restore thread finished Err(_) => { yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from_static(b": keepalive\n\n")); } } } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } /// GET /api/backups/scan-folder?path= — list WolfStack backup files in /// a folder (restore-from-folder / disaster recovery, no backups.json needed). pub async fn backup_scan_folder( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let path = query.get("path").cloned().unwrap_or_default(); if path.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "path required"})); } let safe = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error": e})), }; if is_sensitive_path(&safe) { return HttpResponse::Forbidden().json(serde_json::json!({"error": "That path is off-limits"})); } match backup::scan_backup_folder(&safe.to_string_lossy()) { Ok(list) => HttpResponse::Ok().json(list), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// POST /api/backups/restore-from-path/stream?path=&filename=&overwrite=&storage=&name= /// Restore a backup from a folder + filename WITHOUT a backups.json entry — /// disaster recovery. Proxy this to a chosen node to restore the workload there. pub async fn backup_restore_from_path_stream( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let path = query.get("path").cloned().unwrap_or_default(); let filename = query.get("filename").cloned().unwrap_or_default(); let overwrite = query.get("overwrite").map(|v| v == "true").unwrap_or(false); let storage = query.get("storage").cloned().unwrap_or_default(); let new_name = query.get("name").cloned().unwrap_or_default(); if path.trim().is_empty() || filename.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "path and filename required"})); } let safe = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error": e})), }; if is_sensitive_path(&safe) { return HttpResponse::Forbidden().json(serde_json::json!({"error": "That path is off-limits"})); } let safe_path = safe.to_string_lossy().to_string(); let (std_tx, std_rx) = std::sync::mpsc::channel::(); let (tx, mut rx) = tokio::sync::mpsc::channel::(256); std::thread::spawn(move || { let result = backup::restore_from_path(&safe_path, &filename, overwrite, &storage, &new_name, std_tx.clone()); match result { Ok(msg) => { let _ = std_tx.send(format!("RESULT:OK:{}", msg)); } Err(e) => { let _ = std_tx.send(format!("RESULT:ERR:{}", e)); } } }); tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tx.blocking_send(msg).is_err() { break; } } }); let stream = async_stream::stream! { while let Some(msg) = rx.recv().await { let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } // ── Galera cluster manager ─────────────────────────────────────────── /// Request to create/adopt a Galera cluster. The cluster fields are flattened /// at the top level; `db_password` is the plaintext DB password (encrypted /// server-side, never stored or returned in plaintext). #[derive(serde::Deserialize)] pub struct GaleraSaveRequest { #[serde(flatten)] pub cluster: crate::galera::GaleraCluster, #[serde(default)] pub db_password: String, } /// GET /api/galera/clusters[?cluster=NAME] — list managed clusters (password /// stripped). When `cluster` is given, only that WolfStack cluster's Galera /// clusters are returned (cluster-scoped UI). pub async fn galera_list(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let scope = query.get("cluster").cloned().unwrap_or_default(); let mut cfg = crate::galera::load_config(); // Match the requested scope; also surface legacy clusters (written before // cluster-scoping, `cluster` empty) in every scoped view so an upgrade // doesn't silently hide them — the operator can re-home or forget them. let mut clusters: Vec<_> = cfg.clusters.drain(..) .filter(|c| scope.is_empty() || c.cluster == scope || c.cluster.is_empty()) .collect(); // This node's galera.json holds these clusters, so for the UI's routing // purposes this node IS their owner — ALWAYS stamp it (not just when empty). // A stored owner_node can be stale or point at the build/container host // rather than the config host, which made the UI route status/ops to the // wrong node and get a 404. The host that returns a cluster is where it lives. let self_id = crate::agent::self_node_id(); for c in clusters.iter_mut() { c.db_password_enc = String::new(); c.owner_node = self_id.clone(); } HttpResponse::Ok().json(clusters) } /// POST /api/galera/clusters — create or adopt a cluster (upsert by id). pub async fn galera_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); let mut cluster = b.cluster; if cluster.id.trim().is_empty() { cluster.id = uuid::Uuid::new_v4().to_string(); } if cluster.name.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "cluster name required" })); } if cluster.created_at.is_empty() { cluster.created_at = chrono::Utc::now().to_rfc3339(); } let pw = if b.db_password.is_empty() { None } else { Some(b.db_password.as_str()) }; match crate::galera::upsert_cluster(cluster, pw) { Ok(mut saved) => { saved.db_password_enc = String::new(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "cluster": saved })) } // Most upsert failures are validation (bad name/address) — a client error. Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// One container picked in the adopt UI. #[derive(serde::Deserialize)] pub struct GaleraAdoptNodeReq { #[serde(default)] pub node_id: String, pub container: String, #[serde(default)] pub kind: String, } /// Body for POST /api/galera/adopt. #[derive(serde::Deserialize)] pub struct GaleraAdoptReq { pub cluster_name: String, #[serde(default)] pub cluster: String, #[serde(default)] pub db_user: String, #[serde(default)] pub db_password: String, #[serde(default)] pub sst_method: String, #[serde(default)] pub nodes: Vec, } /// POST /api/galera/adopt — adopt picked containers (LXC/Docker) into a new /// managed cluster. WolfStack resolves each container's address on its host, so /// the operator never types IPs. pub async fn galera_adopt(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); if b.cluster_name.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "cluster name required" })); } if b.nodes.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "select at least one container" })); } let ctx = galera_op_ctx(&state); let picks: Vec = b.nodes.into_iter() .map(|n| crate::galera::AdoptPick { node_id: n.node_id, container: n.container, kind: n.kind }) .collect(); let (name, cluster, sst, user, pass) = (b.cluster_name, b.cluster, b.sst_method, b.db_user, b.db_password); match web::block(move || crate::galera::adopt_cluster(&cluster, &name, &sst, &user, &pass, &picks, &ctx)).await { Ok(Ok(mut saved)) => { saved.db_password_enc = String::new(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "cluster": saved })) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// DELETE /api/galera/clusters/{id} — forget a cluster (does NOT destroy the /// containers; use the per-node controls for that). pub async fn galera_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::galera::delete_cluster(&path.into_inner()) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } /// GET /api/galera/clusters/{id}/status — live wsrep status across all nodes, /// with split-brain detection. pub async fn galera_status(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match crate::galera::get_cluster(&id) { Some(c) => HttpResponse::Ok().json(crate::galera::cluster_status(&c).await), None => HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), } } /// Stream a blocking Galera job (provision/recover) to the browser as SSE. /// `job` runs on a dedicated OS thread (it shells out to lxc/mariadb for /// minutes); its log lines and a final `RESULT:OK:`/`RESULT:ERR:` are relayed. pub(crate) fn galera_stream_job(job: F) -> HttpResponse where F: FnOnce(std::sync::mpsc::Sender) + Send + 'static, { let (std_tx, std_rx) = std::sync::mpsc::channel::(); let (tx, mut rx) = tokio::sync::mpsc::channel::(256); let job_tx = std_tx.clone(); std::thread::spawn(move || { job(job_tx); }); drop(std_tx); // close the original handle so the relay loop ends with the job tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tx.blocking_send(msg).is_err() { break; } } }); let stream = async_stream::stream! { while let Some(msg) = rx.recv().await { let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } /// POST /api/galera/provision — create N new LXC containers on THIS host, install /// MariaDB+Galera, bootstrap a fresh cluster, then persist it. SSE progress. pub async fn galera_provision_stream(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let p = body.into_inner(); let ctx = galera_op_ctx(&state); galera_stream_job(move |tx| { let n = if p.container_names.is_empty() { p.node_count } else { p.container_names.len() }; let _ = tx.send(format!("Provisioning {}-node Galera cluster '{}'…", n, p.cluster_name)); match crate::galera::provision_cluster(&p, &tx, &ctx) { Ok(c) => { let _ = tx.send(format!("RESULT:OK:Cluster '{}' provisioned with {} node(s).", c.name, c.nodes.len())); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } #[derive(serde::Deserialize)] pub struct GaleraBuildReq { pub distribution: String, pub release: String, pub address: String } /// POST /api/galera/local/build/{container} — build a Galera node container on /// THIS host (create + attach the given WolfNet IP + install MariaDB+Galera). /// The cluster's home host calls this on peers when a node lives there. pub async fn galera_local_build(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let container = path.into_inner(); let b = body.into_inner(); match web::block(move || crate::galera::local_build_node(&container, &b.distribution, &b.release, &b.address)).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(serde::Deserialize)] pub struct GaleraLaunchReq { pub distribution: String, pub cluster_name: String, pub gcomm: String, pub node_address: String, pub node_name: String, pub sst_method: String, pub role: String, #[serde(default)] pub root_password: String, } /// POST /api/galera/local/launch/{container} — write the Galera config on a /// built node on THIS host and bootstrap or join it. Home host → peer primitive. pub async fn galera_local_launch(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let container = path.into_inner(); let b = body.into_inner(); match web::block(move || crate::galera::local_launch_node( &container, &b.distribution, &b.cluster_name, &b.gcomm, &b.node_address, &b.node_name, &b.sst_method, &b.role, &b.root_password, )).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// Build the runtime context galera ops need to route per-node work to the host /// that runs each container (cross-host / migrated clusters). Captures the /// current tokio handle so the blocking galera code can drive inter-node HTTP. fn galera_op_ctx(state: &web::Data) -> crate::galera::GaleraOpCtx { crate::galera::GaleraOpCtx { self_id: crate::agent::self_node_id(), nodes: state.cluster.get_all_nodes(), cluster_secret: state.cluster_secret.clone(), rt: tokio::runtime::Handle::current(), } } // ── WolfScale cluster manager (parallels Galera) ───────────────────── fn wolfscale_op_ctx(state: &web::Data) -> crate::wolfscale::WolfScaleOpCtx { crate::wolfscale::WolfScaleOpCtx { self_id: crate::agent::self_node_id(), nodes: state.cluster.get_all_nodes(), cluster_secret: state.cluster_secret.clone(), rt: tokio::runtime::Handle::current(), } } /// GET /api/wolfscale/clusters[?cluster=NAME] — list managed clusters (password /// never returned). Always stamps owner_node = this node so the UI routes ops here. pub async fn wolfscale_list(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let self_id = crate::agent::self_node_id(); let mut cfg = crate::wolfscale::load_config(); let filter = query.get("cluster").cloned(); cfg.clusters.retain(|c| filter.as_ref().map(|f| &c.cluster == f).unwrap_or(true)); for c in cfg.clusters.iter_mut() { c.db_password_enc = String::new(); c.owner_node = self_id.clone(); } HttpResponse::Ok().json(cfg.clusters) } #[derive(serde::Deserialize)] pub struct WolfScaleAdoptReq { pub cluster_name: String, #[serde(default)] pub cluster: String, #[serde(default)] pub db_user: String, #[serde(default)] pub db_password: String, #[serde(default)] pub cluster_port: u16, #[serde(default)] pub api_port: u16, #[serde(default)] pub proxy_port: u16, pub nodes: Vec, } #[derive(serde::Deserialize)] pub struct WolfScaleAdoptNode { #[serde(default)] pub node_id: String, pub container: String, #[serde(default)] pub ws_id: String, } /// POST /api/wolfscale/adopt — adopt picked containers into a managed cluster. pub async fn wolfscale_adopt(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); let name = b.cluster_name.clone(); let ws_cluster = b.cluster.clone(); let user = b.db_user.clone(); let pass = b.db_password.clone(); let (cp, ap, pp) = (b.cluster_port, b.api_port, b.proxy_port); let picks: Vec = b.nodes.into_iter() .map(|n| crate::wolfscale::AdoptPick { node_id: n.node_id, container: n.container, ws_id: n.ws_id }) .collect(); let ctx = wolfscale_op_ctx(&state); match web::block(move || crate::wolfscale::adopt_cluster(&ws_cluster, &name, &user, &pass, cp, ap, pp, &picks, &ctx)).await { Ok(Ok(c)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "id": c.id })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// DELETE /api/wolfscale/clusters/{id} — forget a cluster (containers untouched). pub async fn wolfscale_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::wolfscale::delete_cluster(&path.into_inner()) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/wolfscale/clusters/{id}/status — live status across all nodes. pub async fn wolfscale_status(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match crate::wolfscale::get_cluster(&id) { Some(c) => HttpResponse::Ok().json(crate::wolfscale::cluster_status(&c).await), None => HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), } } /// POST /api/wolfscale/provision — build a fresh WolfScale cluster across hosts. SSE. pub async fn wolfscale_provision_stream(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let p = body.into_inner(); let ctx = wolfscale_op_ctx(&state); galera_stream_job(move |tx| { let n = p.container_names.len(); let _ = tx.send(format!("Provisioning {}-node WolfScale cluster '{}'…", n, p.cluster_name)); match crate::wolfscale::provision_cluster(&p, &tx, &ctx) { Ok(c) => { let _ = tx.send(format!("RESULT:OK:Cluster '{}' provisioned with {} node(s).", c.name, c.nodes.len())); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } /// POST /api/wolfscale/clusters/{id}/nodes/{container}/{action} — start/stop/restart. pub async fn wolfscale_node_action(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container, action) = path.into_inner(); let cluster = match crate::wolfscale::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let ctx = wolfscale_op_ctx(&state); match web::block(move || crate::wolfscale::node_service(&cluster, &container, &action, &ctx)).await { Ok(Ok(_)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/wolfscale/clusters/{id}/nodes/{container}/admin/{action} — promote/demote. pub async fn wolfscale_node_admin(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container, action) = path.into_inner(); let cluster = match crate::wolfscale::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; match crate::wolfscale::node_admin(&cluster, &container, &action).await { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/wolfscale/local/setup/{container} — build one node on THIS host. pub async fn wolfscale_local_setup(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let container = path.into_inner(); let spec = body.into_inner(); // The URL names the container; the body must agree (don't let a caller build // an arbitrary container by mismatching the path and the spec). if spec.container != container { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "container in URL and body must match" })); } match web::block(move || crate::wolfscale::local_setup_node(&spec)).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/wolfscale/local/op/{action}/{container} — run a node op on THIS host. pub async fn wolfscale_local_op(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (action, container) = path.into_inner(); let op = match crate::wolfscale::NodeOp::from_str(&action) { Some(o) => o, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown op '{}'", action) })), }; match web::block(move || crate::wolfscale::local_node_op(&container, op)).await { Ok(Ok(output)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/galera/clusters/{id}/recover — evidence-based recovery: stop all /// nodes, bootstrap the most-advanced (highest grastate seqno), rejoin the rest. /// Refuses to act when no node reports a known position. SSE progress. pub async fn galera_recover_stream(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let ctx = galera_op_ctx(&state); galera_stream_job(move |tx| { let _ = tx.send(format!("Recovering cluster '{}'…", cluster.name)); match crate::galera::recover_cluster(&cluster, &tx, &ctx) { Ok(msg) => { let _ = tx.send(format!("RESULT:OK:{}", msg)); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } /// POST /api/galera/clusters/{id}/nodes/{container}/{action} — start/stop/restart /// MariaDB on one node, routed to the host that currently runs the container. pub async fn galera_node_action(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container, action) = path.into_inner(); let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let ctx = galera_op_ctx(&state); match web::block(move || crate::galera::node_service(&cluster, &container, &action, &ctx)).await { Ok(Ok(_)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/galera/local/{kind}/{op}/{container} — run ONE galera node op on a /// container (LXC or Docker) that lives on THIS host. The cluster-owning node /// calls this on peer hosts (over the inter-node channel) to manage nodes that /// sit elsewhere. Accepts a session OR the inter-node cluster secret. pub async fn galera_local_node_op(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (kind, op_s, container) = path.into_inner(); if !matches!(kind.as_str(), "lxc" | "docker") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown container kind '{}'", kind) })); } let op = match crate::galera::NodeOp::from_str(&op_s) { Some(o) => o, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown galera node op '{}'", op_s) })), }; match web::block(move || crate::galera::local_node_op(&kind, &container, op)).await { Ok(Ok(output)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/galera/clusters/{id}/add-nodes — grow an existing cluster with new /// MariaDB+Galera nodes built on the cluster's owner host, joined via SST. SSE. pub async fn galera_add_nodes_stream(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let p = body.into_inner(); let ctx = galera_op_ctx(&state); galera_stream_job(move |tx| { let _ = tx.send(format!("Adding {} node(s) to '{}'…", p.container_names.len(), cluster.name)); match crate::galera::add_nodes(&cluster, &p, &tx, &ctx) { Ok(c) => { let _ = tx.send(format!("RESULT:OK:'{}' now has {} node(s).", c.name, c.nodes.len())); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } /// POST /api/galera/clusters/{id}/maxscale — provision a MaxScale proxy /// pre-configured for this cluster (galeramon + readwritesplit). SSE. pub async fn galera_maxscale_stream(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let p = body.into_inner(); let ctx = galera_op_ctx(&state); galera_stream_job(move |tx| { let _ = tx.send(format!("Provisioning MaxScale proxy '{}' for '{}'…", p.container_name, cluster.name)); match crate::galera::provision_maxscale(&cluster, &p, &tx, &ctx) { Ok(c) => { let _ = tx.send(format!("RESULT:OK:MaxScale proxy is up for '{}'.", c.name)); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } #[derive(serde::Deserialize)] pub struct GaleraGcommReq { pub gcomm: String } /// POST /api/galera/local/gcomm/{kind}/{container} — rewrite a node's gcomm seed /// list on THIS host. The cluster owner calls this on peer hosts (over the /// inter-node channel) when growing a cluster. Accepts a session OR the secret. pub async fn galera_local_set_gcomm(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (kind, container) = path.into_inner(); if !matches!(kind.as_str(), "lxc" | "docker") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown container kind '{}'", kind) })); } let gcomm = body.into_inner().gcomm; match web::block(move || crate::galera::set_gcomm_local(&kind, &container, &gcomm)).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// DELETE /api/galera/clusters/{id}/proxies/{container} — stop + forget a /// MaxScale proxy (leaves the stopped container for the operator to delete). pub async fn galera_remove_proxy(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container) = path.into_inner(); match web::block(move || crate::galera::remove_proxy(&id, &container)).await { Ok(Ok(_)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// GET /api/galera/clusters/{id}/analyze — per-node tuning analysis (advisory). pub async fn galera_analyze(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; let sqls = crate::galera::analyze_sql(&cluster).await; let ctx = galera_op_ctx(&state); match web::block(move || crate::galera::build_analysis(&cluster, sqls, &ctx)).await { Ok(a) => HttpResponse::Ok().json(a), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(serde::Deserialize)] pub struct GaleraTuneReq { pub key: String, pub value: String } /// POST /api/galera/clusters/{id}/tune — apply one setting cluster-wide: SET /// GLOBAL live on every reachable node (dynamic settings) + persist to a managed /// config include so it survives restart. Allowlist-gated. pub async fn galera_apply_tuning(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let b = body.into_inner(); let dynamic = match crate::galera::is_tunable(&b.key) { Some(d) => d, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("'{}' is not a tunable setting", b.key) })), }; if b.value.is_empty() || !b.value.chars().all(|c| c.is_ascii_digit()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "value must be a non-negative integer" })); } let cluster = match crate::galera::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("cluster '{}' not found", id) })), }; // 1. Live SET GLOBAL (dynamic only). let live = if dynamic { crate::galera::set_global_cluster(&cluster, &b.key, &b.value).await } else { vec![] }; // 2. Persist to the managed include on every node (host-aware). let ctx = galera_op_ctx(&state); let (cluster2, key2, val2) = (cluster.clone(), b.key.clone(), b.value.clone()); let persist = web::block(move || crate::galera::persist_tuning_cluster(&cluster2, &key2, &val2, &ctx)).await .unwrap_or_else(|e| vec![(String::new(), Err(e.to_string()))]); type TuningOutcome = (Option, Option, Option, Option); let mut map: std::collections::HashMap = std::collections::HashMap::new(); for (c, r) in live { let e = map.entry(c).or_default(); e.0 = Some(r.is_ok()); e.1 = r.err(); } for (c, r) in persist { let e = map.entry(c).or_default(); e.2 = Some(r.is_ok()); e.3 = r.err(); } let nodes: Vec<_> = map.into_iter().map(|(c, (lo, le, po, pe))| serde_json::json!({ "container": c, "applied_live": lo, "live_error": le, "persisted": po, "persist_error": pe, })).collect(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "key": b.key, "value": b.value, "dynamic": dynamic, "requires_restart": !dynamic, "nodes": nodes })) } /// POST /api/galera/local/tuning/{kind}/{container} — persist one setting into a /// container that lives on THIS host (called by the owner over the inter-node /// channel for cross-host nodes). Allowlist-gated. pub async fn galera_local_tuning(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (kind, container) = path.into_inner(); if !matches!(kind.as_str(), "lxc" | "docker") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown container kind '{}'", kind) })); } let b = body.into_inner(); match web::block(move || crate::galera::write_tuning_local(&kind, &container, &b.key, &b.value)).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } // ═══ PostgreSQL HA (streaming replication) — Noro stage 2 ═══ // Mirrors the Galera API. Postgres HA clusters are placed onto Database-role // nodes (the roles keystone), one primary + N streaming standbys. /// GET /api/postgres-ha/clusters — list managed PG HA clusters (this node's /// config, scoped by ?cluster=). Passwords are never returned. pub async fn pgha_list(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let scope = query.get("cluster").cloned().unwrap_or_default(); let self_id = crate::agent::self_node_id(); let mut clusters: Vec<_> = crate::postgres_ha::load_config().clusters.into_iter() .filter(|c| scope.is_empty() || c.cluster == scope || c.cluster.is_empty()) .collect(); for c in clusters.iter_mut() { c.db_password_enc = String::new(); c.repl_password_enc = String::new(); c.owner_node = self_id.clone(); } HttpResponse::Ok().json(clusters) } /// GET /api/postgres-ha/clusters/{id}/status — live replication status. pub async fn pgha_status(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let Some(cluster) = crate::postgres_ha::get_cluster(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "cluster not found" })); }; match web::block(move || crate::postgres_ha::cluster_status(&cluster)).await { Ok(st) => HttpResponse::Ok().json(st), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// GET /api/postgres-ha/placement?want=N — recommended Database-role hosts for /// a new N-node cluster. Surfaces the tier so the operator confirms rather than /// hand-picks. Warns (in `enough`) when fewer than `want` DB nodes exist. pub async fn pgha_placement(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let want: usize = query.get("want").and_then(|v| v.parse().ok()).unwrap_or(3); let ids = crate::postgres_ha::recommend_placement(&state.cluster, want); let nodes: Vec = ids.iter().filter_map(|id| { state.cluster.get_node(id).map(|n| serde_json::json!({ "id": n.id, "hostname": n.display_name.clone().unwrap_or(n.hostname), "address": n.address, })) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "want": want, "available": nodes.len(), "enough": nodes.len() >= want, "nodes": nodes, })) } /// POST /api/postgres-ha/provision — create the containers, install Postgres, /// configure streaming replication, persist. SSE progress (reuses the Galera /// streaming-job relay). Members must live on THIS node for v1 (single-host or /// operator points each at its owner); cross-host fan-out is a follow-up. pub async fn pgha_provision_stream(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let p = body.into_inner(); let self_id = crate::agent::self_node_id(); galera_stream_job(move |tx| { let _ = tx.send(format!("Provisioning Postgres HA cluster '{}' ({} node(s))…", p.name, p.members.len())); match crate::postgres_ha::provision_cluster_local(&p, &tx) { Ok(mut c) => { c.owner_node = self_id; match crate::postgres_ha::upsert_cluster(c) { Ok(c) => { let _ = tx.send(format!("RESULT:OK:Cluster '{}' provisioned with {} node(s).", c.name, c.nodes.len())); } Err(e) => { let _ = tx.send(format!("RESULT:ERR:persist failed: {}", e)); } } } Err(e) => { let _ = tx.send(format!("RESULT:ERR:{}", e)); } } }) } /// POST /api/postgres-ha/clusters/{id}/promote/{container} — promote a standby. pub async fn pgha_promote(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container) = path.into_inner(); let Some(cluster) = crate::postgres_ha::get_cluster(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "cluster not found" })); }; match web::block(move || crate::postgres_ha::promote_standby(&cluster, &container)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/postgres-ha/clusters/{id}/node/{container}/{action} — start/stop/restart. pub async fn pgha_node_action(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (id, container, action) = path.into_inner(); let Some(cluster) = crate::postgres_ha::get_cluster(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "cluster not found" })); }; match web::block(move || crate::postgres_ha::node_service(&cluster, &container, &action)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// DELETE /api/postgres-ha/clusters/{id} — forget a cluster definition (does /// NOT destroy the containers; mirrors Galera delete semantics). pub async fn pgha_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match crate::postgres_ha::delete_cluster(&id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } // ═══ HA mail tier — Noro stage 3 ═══ // Topology + MX publishing from the Mail / MailRelay roles. MX/A records are // published through the DNS tier's own fan-out (stage 1), so one mechanism // writes them to every nameserver. /// GET /api/mail-tier/status — the mail tier as derived from node roles. pub async fn mail_tier_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(crate::mail_tier::status(&state.cluster)) } /// GET /api/mail-tier/domain/{domain}/records — the MX + A records that would /// publish this tier for `domain` (preview; publish applies them). pub async fn mail_tier_records(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let domain = path.into_inner(); let tier = crate::mail_tier::MailTier::from_cluster(&state.cluster); HttpResponse::Ok().json(serde_json::json!({ "domain": domain, "records": crate::mail_tier::mx_records_for(&domain, &tier), })) } /// Publish one DNS record to every `dns`-role node, reusing the stage-1 apply /// endpoint (self via the local function, remotes via the node proxy). Returns /// (applied, errors). Shared by the mail tier's MX publishing. async fn publish_record_to_dns_tier( state: &web::Data, domain: &str, name: &str, rtype: &str, content: &str, ttl: u32, ) -> (usize, Vec) { let dns_nodes: Vec = state.cluster.nodes_with_role(crate::agent::NodeRole::Dns); let body = serde_json::json!({ "domain": domain, "name": name, "type": rtype, "content": content, "ttl": ttl, "delete": false, }); // No DNS tier → nothing to publish to; report as an error so the caller // surfaces "assign the DNS role first" rather than silently succeeding. if dns_nodes.is_empty() { return (0, vec!["no dns-role nodes — assign the DNS role to at least one node first".into()]); } let self_id = crate::agent::self_node_id(); let mut ok = 0usize; let mut errs = Vec::new(); let client = &*API_HTTP_CLIENT; for n in &dns_nodes { if n.id == self_id || n.is_self { // Apply locally, off-thread (pdns provisioning is blocking). let (d, nm, rt, ct) = (domain.to_string(), name.to_string(), rtype.to_string(), content.to_string()); let r = web::block(move || { crate::wolfhost::provisioning::dns::set_record(&d, &nm, &rt, &ct, ttl) }).await; match r { Ok(Ok(())) => ok += 1, Ok(Err(e)) => errs.push(format!("{}: {}", n.id, e)), Err(e) => errs.push(format!("{}: {}", n.id, e)) } } else { let urls = build_node_urls(&n.address, n.port, "/api/wolfhost-dns/record"); let mut done = false; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&state.cluster_secret) .header("Content-Type", "application/json") .body(body.to_string()) .send().await && resp.status().is_success() { let _ = resp.bytes().await; done = true; break; } } if done { ok += 1; } else { errs.push(format!("{}: unreachable", n.id)); } } } (ok, errs) } /// POST /api/mail-tier/domain/{domain}/publish — generate the MX/A records for /// this tier and write them to every DNS-role nameserver via the DNS fan-out. pub async fn mail_tier_publish(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let domain = path.into_inner(); let tier = crate::mail_tier::MailTier::from_cluster(&state.cluster); if !tier.has_store() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "no Mail-role nodes — assign the Mail role to at least one node first", })); } let records = crate::mail_tier::mx_records_for(&domain, &tier); let mut published = 0usize; let mut errors: Vec = Vec::new(); for r in &records { let (ok, errs) = publish_record_to_dns_tier(&state, &domain, &r.name, &r.rtype, &r.content, r.ttl).await; if ok > 0 { published += 1; } errors.extend(errs); } let body = serde_json::json!({ "domain": domain, "records_published": published, "records_total": records.len(), "errors": errors, "note": "MX/A records published to the DNS tier. Postfix relay and dovecot replication config are available from /api/mail-tier/config-preview for the operator to apply to the tier's nodes; live cluster failover needs hardware verification.", }); // Total failure (nothing published) is an error, not a 200 — mirrors the // DNS fan-out's own semantics. if published == 0 { return HttpResponse::InternalServerError().json(body); } HttpResponse::Ok().json(body) } // ═══ Website failover across Host-role nodes — Noro stage 4 ═══ /// GET /api/site-failover/status — hosted sites + their failover plan. pub async fn site_failover_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(crate::site_failover::status(&state.cluster)) } #[derive(serde::Deserialize)] pub struct HostedSiteReq { pub domain: String, pub docroot: String, #[serde(default)] pub active_host: String, #[serde(default)] pub cluster: String, #[serde(default)] pub port: Option, } /// POST /api/site-failover/sites — register/update a hosted site. When /// `active_host` is empty, the first online Host node is chosen. pub async fn site_failover_upsert(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); if b.domain.trim().is_empty() || b.docroot.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "domain and docroot are required" })); } let active = if b.active_host.trim().is_empty() { crate::site_failover::online_host_ids(&state.cluster).into_iter().next().unwrap_or_default() } else { b.active_host.trim().to_string() }; let site = crate::site_failover::HostedSite { domain: b.domain.trim().to_string(), docroot: b.docroot.trim().to_string(), active_host: active, cluster: b.cluster, port: b.port.unwrap_or(80), }; match crate::site_failover::upsert_site(site) { Ok(s) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "site": s })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/site-failover/sites/{domain} — stop tracking a site. pub async fn site_failover_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::site_failover::delete_site(&path.into_inner()) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } /// POST /api/site-failover/sites/{domain}/reassign/{host} — move a site to a /// Host node and re-point the ingress to it. The re-point reuses the same /// router-config replication the Internet Exposure reconciler uses. pub async fn site_failover_reassign(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (domain, host) = path.into_inner(); // Refuse a reassignment to a host that isn't an online Host node. let online = crate::site_failover::online_host_ids(&state.cluster); if !online.iter().any(|id| id == &host) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("'{}' is not an online Host-role node", host), })); } match crate::site_failover::reassign_site(&domain, &host) { Ok(s) => { // The router owns the actual ingress re-point; record the new // upstream host so the exposure/router reconcile picks it up. let target_addr = state.cluster.get_node(&host).map(|n| n.address).unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "site": s, "upstream_host": target_addr, "note": "Active host updated; the ingress re-points to it on the next router reconcile. Verify the shared docroot mount is present on the target host.", })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/mail-tier/config-preview?domains=a.com,b.com — the exact Postfix /// relay config (for MailRelay nodes) and dovecot replication config (for Mail /// store nodes) this tier would apply. Surfacing it lets the operator review /// and apply it, and documents the tier's runtime shape. pub async fn mail_tier_config_preview(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let tier = crate::mail_tier::MailTier::from_cluster(&state.cluster); let domains: Vec = query.get("domains") .map(|s| s.split(',').map(|d| d.trim().to_string()).filter(|d| !d.is_empty()).collect()) .unwrap_or_default(); let store_addrs: Vec = tier.store_nodes.iter().map(|n| n.address.clone()).collect(); let (relay_domains, transport_maps) = crate::mail_tier::relay_config(&domains, &store_addrs); // Each store node replicates from its partners (the other store nodes). let replication: Vec = tier.store_nodes.iter().map(|n| { let partners: Vec = tier.store_nodes.iter() .filter(|p| p.node_id != n.node_id) .map(|p| p.address.clone()) .collect(); serde_json::json!({ "node": n.hostname, "address": n.address, "dovecot_replication_conf": crate::mail_tier::dovecot_replication_config(&partners), }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "relay": { "relay_domains": relay_domains, "transport_maps": transport_maps }, "replication": replication, })) } /// DELETE /api/backups/{id} — delete a backup entry + file pub async fn backup_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // delete_backup now drives S3 object deletes (thread+join) and remote-peer // deletes (curl, up to 60s) — sync blocking work that must not run on the // actix worker. Offload like backup_delete_failed already does. let id = path.into_inner(); match web::block(move || backup::delete_backup(&id)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("task failed: {}", e) })), } } /// POST /api/backups/delete-failed — remove every failed backup entry + file pub async fn backup_delete_failed(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(backup::delete_failed_backups).await { Ok(Ok(removed)) => HttpResponse::Ok().json(serde_json::json!({ "removed": removed, "message": format!("Removed {} failed backup{}", removed, if removed == 1 { "" } else { "s" }), })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("task failed: {}", e) })), } } /// POST /api/backups/{id}/restore — restore from a backup pub async fn backup_restore( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let overwrite = query.get("overwrite").map(|v| v == "true").unwrap_or(false); match backup::restore_by_id(&path.into_inner(), overwrite) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) if e.starts_with("CONTAINER_EXISTS:") => { let name = e.strip_prefix("CONTAINER_EXISTS:").unwrap_or(""); HttpResponse::Conflict().json(serde_json::json!({ "error": "container_exists", "container": name, "message": format!("Container '{}' already exists. Overwrite?", name) })) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/backups/targets — list available backup targets pub async fn backup_targets( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(backup::list_available_targets()) } /// GET /api/backup/mounts/{type}/{name} — list a container's bind/volume /// mounts so the UI can offer an "exclude from backup" checklist. `type` is /// `docker` or `lxc`. Returns `[{type,source,destination,size_bytes}]`. pub async fn backup_container_mounts( req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (kind, name) = path.into_inner(); let result = web::block(move || match kind.as_str() { "docker" => backup::discover_docker_mounts(&name), "lxc" => backup::discover_lxc_mounts(&name), other => Err(format!("Unknown container type '{}' (expected docker|lxc)", other)), }).await; match result { Ok(Ok(mounts)) => HttpResponse::Ok().json(mounts), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("mount discovery task: {}", e), })), } } #[derive(Debug, Deserialize)] pub struct MountCheckTarget { #[serde(rename = "type")] pub target_type: String, pub name: String, /// Mounts the operator has already excluded for this target — skipped, so /// a decision they have already made isn't re-asked every save. #[serde(default)] pub exclude_mounts: Vec, } #[derive(Debug, Deserialize)] pub struct MountCheckRequest { #[serde(default)] pub targets: Vec, } /// POST /api/backup/mount-check — which of these targets carry a bind/volume /// mount big enough to warn about before the backup is saved or started. /// /// Body: `{"targets":[{"type":"docker","name":"nextcloud","exclude_mounts":[…]},…]}` /// — the same shape the picker already holds, exclusions included, so the /// answer reflects what this backup would ACTUALLY archive. Non-container /// targets are ignored rather than rejected: the caller passes its whole /// selection. /// /// The threshold comes back with the answer so the dialog's wording can never /// drift from the figure the backend applied. pub async fn backup_mount_check( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let targets: Vec<(String, String, Vec)> = body .into_inner() .targets .into_iter() .filter(|t| !t.name.trim().is_empty()) .map(|t| (t.target_type, t.name, t.exclude_mounts)) .collect(); // Sizing shells out to df/du — blocking work, off the runtime. match web::block(move || backup::large_mounts_for_targets(&targets)).await { Ok((findings, unchecked)) => HttpResponse::Ok().json(serde_json::json!({ "threshold_bytes": backup::LARGE_MOUNT_WARN_BYTES, "findings": findings, "unchecked": unchecked, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("mount check task: {}", e), })), } } // ─── Fleet-scope backup configuration ─── // // A schedule saved at FLEET scope in the GUI landed only on the node that // served the request: wolf1 got `schedules[0]` and ran a backup two minutes // later, while wolf2 and wolf3 kept `schedules: []` and would never have run // one. Nothing was logged, so it looked like it had worked (production report, // 3-node "wolf" cluster, 2026-07-30). // // The transport was never the problem — the same cluster fans auth lockouts out // fine ("kernel-blocked via fleet propagation from ws-xxxx"). The backup // path simply never used it. This is that path, built on the same pieces // `propagate_kernel_block_to_peers` uses: peers from ClusterState, the // HTTPS-first `build_node_urls` chain, `X-WolfStack-Secret`, the pooled client. // // Doing it server-side rather than in the browser matters: `pushClusterSchedule` // already fanned out client-side, which silently requires the OPERATOR'S BROWSER // to reach every node directly. On a cluster whose peers talk over WolfNet but // aren't individually reachable from the admin's laptop, that fails per node — // and the browser can only report what it could reach. /// Where a backup configuration write applies. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)] #[serde(rename_all = "lowercase")] pub enum BackupScope { /// This node only. The default, and what every existing caller sends by /// omitting the field — so their behaviour is byte-identical. #[default] Node, /// Every WolfStack node in the cluster. Fleet, } /// Aggregate per-node results into the response body the GUI renders. /// /// `failed > 0` is what the GUI keys its visible error off. A fleet write that /// reached two nodes out of three is NOT a success — the third has no schedule /// and will never run one, which is the whole defect. `skipped` is counted /// separately: a PVE or TrueNAS member has no backups.json and its absence from /// the write is correct, not a failure to wave at the operator. pub fn fleet_result_summary(results: &[FleetNodeResult]) -> serde_json::Value { let succeeded = results.iter().filter(|r| r.status == "ok").count(); let failed = results.iter().filter(|r| r.status == "failed").count(); let skipped = results.iter().filter(|r| r.status == "skipped").count(); serde_json::json!({ "scope": "fleet", "total": succeeded + failed, "succeeded": succeeded, "failed": failed, "skipped": skipped, "results": results, }) } /// The hostnames that did NOT take a fleet write, formatted for an operator. pub fn fleet_failed_nodes(results: &[FleetNodeResult]) -> Vec { results.iter() .filter(|r| r.status == "failed") .map(|r| format!("{} ({})", r.hostname, r.error.clone().unwrap_or_default())) .collect() } #[cfg(test)] mod fleet_backup_scope_tests { use super::*; fn result(host: &str, status: &str, err: Option<&str>) -> FleetNodeResult { FleetNodeResult { node_id: format!("ws-{}", host), hostname: host.to_string(), address: format!("10.0.0.{}", host.len()), status: status.to_string(), data: if status == "ok" { Some(serde_json::json!({"ok": true})) } else { None }, error: err.map(|e| e.to_string()), } } /// The defect, as a test: a fleet-scope write must land on ALL N nodes. /// Production had wolf1 with the schedule and wolf2/wolf3 with /// `schedules: []`, reported as success. #[test] fn a_fleet_write_that_reaches_every_node_reports_all_of_them() { let results = vec![ result("wolf1", "ok", None), result("wolf2", "ok", None), result("wolf3", "ok", None), ]; let s = fleet_result_summary(&results); assert_eq!(s["total"], 3, "all three nodes accounted for"); assert_eq!(s["succeeded"], 3); assert_eq!(s["failed"], 0); assert!(fleet_failed_nodes(&results).is_empty()); } /// The production symptom must now be reported as a failure, not silence. #[test] fn a_write_that_reached_only_the_serving_node_is_a_failure() { let results = vec![ result("wolf1", "ok", None), result("wolf2", "failed", Some("transport: connection refused")), result("wolf3", "failed", Some("HTTP 403: Invalid cluster secret")), ]; let s = fleet_result_summary(&results); assert_eq!(s["succeeded"], 1); assert_eq!(s["failed"], 2, "two nodes have NO schedule — that is an error"); let failed = fleet_failed_nodes(&results); assert_eq!(failed.len(), 2); // The operator needs to know WHICH node and WHY, not just a count. assert!(failed[0].contains("wolf2") && failed[0].contains("connection refused")); assert!(failed[1].contains("wolf3") && failed[1].contains("Invalid cluster secret")); } /// A node that legitimately has no backups.json must not be reported as a /// failure, or every mixed cluster would show a permanent red cross. #[test] fn non_wolfstack_members_are_skipped_not_failed() { let results = vec![ result("wolf1", "ok", None), result("pve1", "skipped", Some("non-WolfStack node")), ]; let s = fleet_result_summary(&results); assert_eq!(s["total"], 1, "skipped nodes are not part of the N"); assert_eq!(s["succeeded"], 1); assert_eq!(s["failed"], 0); assert_eq!(s["skipped"], 1); assert!(fleet_failed_nodes(&results).is_empty()); } /// Absent `scope` must mean node-local, so every existing frontend and any /// stored request shape keeps its exact behaviour. #[test] fn scope_defaults_to_node_for_callers_that_never_heard_of_it() { let req: CreateScheduleRequest = serde_json::from_value(serde_json::json!({ "name": "nightly", "frequency": "daily", "time": "02:00", "retention": 7, "backup_all": true, "storage": { "type": "local", "path": "/var/backups" } })).expect("a pre-fleet request body must still deserialize"); assert_eq!(req.scope, BackupScope::Node); assert!(req.enabled, "enabled still defaults true"); } #[test] fn fleet_scope_is_opt_in_by_name() { let req: CreateScheduleRequest = serde_json::from_value(serde_json::json!({ "name": "nightly", "frequency": "daily", "time": "02:00", "retention": 7, "backup_all": true, "storage": { "type": "local", "path": "/var/backups" }, "scope": "fleet" })).unwrap(); assert_eq!(req.scope, BackupScope::Fleet); } } #[derive(Deserialize, Serialize, Clone)] pub struct RemoveBackupServerRequest { /// Host, optionally with a port — "node3.dreamhosting.at:8007". pub server: String, /// Narrow to one datastore/bucket/share; empty removes every reference. #[serde(default)] pub datastore: String, /// Proceed even though schedules still target the server, deleting them. /// Default false: the first call REPORTS what would break, and the operator /// confirms. #[serde(default)] pub force: bool, /// Restrict to these node ids; empty means the whole fleet. #[serde(default)] pub target_nodes: Vec, } /// POST /api/backups/servers/remove — remove a backup server fleet-wide. /// /// Idempotent: re-running against clean nodes reports zeroes and succeeds, /// which is what makes a partial fan-out safe to retry. pub async fn backup_server_remove( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let request = body.into_inner(); if request.server.trim().is_empty() { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "A server hostname is required" })); } let payload = serde_json::to_value(&request).unwrap_or(serde_json::json!({})); let self_targeted = request.target_nodes.is_empty() || request.target_nodes.contains(&state.cluster.self_id); let local = if self_targeted { let target = backup::BackupServerRef { server: request.server.clone(), datastore: request.datastore.clone(), }; let force = request.force; // Filesystem work — off the async executor. Some(web::block(move || backup::remove_backup_server(&target, force)) .await .unwrap_or_else(|e| Err(format!("local removal panicked: {}", e))) .and_then(|r| serde_json::to_value(r).map_err(|e| e.to_string()))) } else { None }; let results = fleet_fanout_post::( &state, "/api/backups/servers/remove-local", payload, &request.target_nodes, local, FANOUT_SLOW, ).await; // A node that refused because a schedule still targets the server is NOT a // failure — it is the guard doing its job, and it must be reported // distinctly so the GUI can offer "remove anyway" rather than "retry". let mut blocked: Vec = Vec::new(); for r in &results { if let Some(data) = &r.data { let names: Vec = data.get("blocking_schedules") .and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()) .unwrap_or_default(); if !names.is_empty() { blocked.push(format!("{}: {}", r.hostname, names.join(", "))); } } } let summary = fleet_result_summary(&results); let failed = summary["failed"].as_u64().unwrap_or(0); tracing::info!( "backup server removal '{}': {} ok, {} failed, {} blocked by schedules", request.server, summary["succeeded"], failed, blocked.len(), ); let mut payload = serde_json::json!({ "server": request.server, "fleet": summary, "blocked_by_schedules": blocked, }); if !blocked.is_empty() && !request.force { payload["error"] = serde_json::Value::String(format!( "Schedules still back up to {} on: {}. Repoint or delete them, or re-run with force to delete them.", request.server, blocked.join("; "), )); return HttpResponse::Conflict().json(payload); } if failed > 0 { payload["error"] = serde_json::Value::String(format!( "{} node(s) still hold this server's configuration: {}", failed, fleet_failed_nodes(&results).join("; "), )); return HttpResponse::MultiStatus().json(payload); } HttpResponse::Ok().json(payload) } /// POST /api/backups/servers/remove-local — inter-node receiver. Removes on /// THIS node only and never fans out again. pub async fn backup_server_remove_local( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let request = body.into_inner(); let target = backup::BackupServerRef { server: request.server.clone(), datastore: request.datastore.clone(), }; let force = request.force; match web::block(move || backup::remove_backup_server(&target, force)).await { Ok(Ok(report)) => { if !report.blocking_schedules.is_empty() { tracing::info!( "backup server removal '{}' refused: schedules still target it: {}", request.server, report.blocking_schedules.join(", "), ); } else if !report.is_noop() { tracing::info!( "backup server removal '{}': {}", request.server, report.details.join("; "), ); } HttpResponse::Ok().json(report) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("removal task failed: {}", e) })), } } /// POST /api/backups/schedules/fleet-apply — inter-node receiver. /// /// Applies a schedule locally and does NOT fan out again; the originating node /// talks to every peer directly, so a peer that re-propagated would multiply /// the write by N on every hop. Same loop-avoidance the federation kernel-block /// endpoint relies on. pub async fn backup_schedule_fleet_apply( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // require_auth accepts a peer's cluster secret OR an operator session — // matching security_kernel_block_ip, which had to be widened for exactly // this reason (peers running a custom cluster secret were rejected). if let Err(e) = require_auth(&req, &state) { return e; } let schedule = body.into_inner(); let name = schedule.name.clone(); match backup::save_schedule(schedule) { Ok(s) => { tracing::info!("backup fleet apply: stored schedule '{}' ({})", s.name, s.id); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "id": s.id })) } Err(e) => { tracing::warn!("backup fleet apply: refused schedule '{}': {}", name, e); HttpResponse::BadRequest().json(serde_json::json!({ "ok": false, "error": e })) } } } pub async fn backup_schedules_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Redacted: this response reached the browser carrying `pbs_password` and // friends in cleartext. The edit dialog re-posts the schedule it was shown, // so `backup_schedule_create` restores any sentinel from the stored // schedule before saving — without that pairing an edit would persist the // bullets and the 02:00 run would fail to authenticate. let mut schedules = crate::secrets::to_redacted_json(&backup::list_schedules()); // `running` is live state, not stored: it lets the table show a run in // progress and hold the "Run now" button until it has finished. if let Some(rows) = schedules.as_array_mut() { for row in rows { let running = row.get("id").and_then(|v| v.as_str()) .map(backup::schedule_run_in_progress).unwrap_or(false); if let Some(obj) = row.as_object_mut() { obj.insert("running".into(), serde_json::Value::Bool(running)); } } } HttpResponse::Ok().json(schedules) } /// POST /api/backups/test-storage — try to set up the destination (mount /// NFS/SMB, create local dir, etc.) without actually backing anything up. /// Lets the UI pre-validate a schedule before saving it and surface a /// MISSING_PACKAGE marker at save time — otherwise the user only sees /// failures hours later in the backup history. #[derive(Deserialize)] pub struct TestStorageRequest { pub storage: backup::BackupStorage, } pub async fn backup_test_storage( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match backup::test_storage(&body.storage) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// POST /api/backups/schedules — create or update a schedule pub async fn backup_schedule_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Cluster-wide scheduler UI sends only `{type:"pbs"}`; fill in saved // server/credentials so the schedule is runnable without a second round-trip. let mut storage = body.storage.clone(); // Validate the WolfDisk subpath at the schedule-save boundary // too — a recurring schedule that resolves to a sanitized path // would silently write to the wrong place every night. if matches!(storage.storage_type, backup::StorageType::Wolfdisk) && let Err(e) = backup::BackupStorage::validate_wolfdisk_subpath(&storage.wolfdisk_subpath) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } // Edit vs create: when the body carries an existing id, update that schedule in // place and PRESERVE its created_at + last_run (otherwise an edit would reset the // freshness clock and lose "last ran" history). Absent id = brand-new schedule. let editing = body.id.as_deref() .filter(|id| !id.is_empty()) .and_then(|id| backup::list_schedules().into_iter().find(|s| s.id == id)); // Put back any credential the browser sent as the redaction sentinel. // `backup_schedules_list` masks secrets, and the edit dialog re-posts the // schedule it was shown verbatim (`storage = editing.storage`), so every // edit arrives with "••••••••" where the password was. Restoring from the // stored schedule keeps the credential; the merge also guarantees no // sentinel is ever persisted, so a sentinel with nothing behind it becomes // empty and `merge_pbs_secrets` fills it from the saved connection below. // This must run BEFORE merge_pbs_secrets: an empty field is what tells that // function to supply the saved value. storage = match crate::secrets::merge_incoming_secrets( &storage, editing.as_ref().map(|s| &s.storage), ) { Ok(s) => s, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; backup::merge_pbs_secrets(&mut storage); // Day pinning is validated here, at the boundary: a bad value would be // stored and then silently never match, so the schedule would simply never // run — the failure mode that has to be loud, not tolerated. if let Some(dow) = body.day_of_week && !(1..=7).contains(&dow) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("day_of_week must be 1 (Monday) to 7 (Sunday), got {}", dow), })); } if let Some(dom) = body.day_of_month && !(1..=31).contains(&dom) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("day_of_month must be 1 to 31, got {}", dom), })); } let is_edit = editing.is_some(); let schedule = backup::BackupSchedule { id: editing.as_ref().map(|s| s.id.clone()) .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()), name: body.name.clone(), frequency: body.frequency.clone(), time: body.time.clone(), retention: body.retention, backup_all: body.backup_all, targets: body.targets.clone(), storage, enabled: body.enabled, last_run: editing.as_ref().map(|s| s.last_run.clone()).unwrap_or_default(), created_at: editing.as_ref().map(|s| s.created_at.clone()) .filter(|c| !c.is_empty()) .unwrap_or_else(|| chrono::Utc::now().to_rfc3339()), pre_command: body.pre_command.clone(), post_command: body.post_command.clone(), // Day pinning + cold-container backups. Only meaningful for the matching // frequency / backup_all combination; stored verbatim either way so // switching a schedule back to weekly keeps the day it had. day_of_week: body.day_of_week, day_of_month: body.day_of_month, stop_containers: body.stop_containers, keep_vms_running: body.keep_vms_running, docker_mounts_only: body.docker_mounts_only, }; // Node scope: unchanged from before fleet scope existed. if body.scope == BackupScope::Node { return match backup::save_schedule(schedule) { Ok(s) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Schedule '{}' {}", s.name, if is_edit { "updated" } else { "created" }), // Redacted like the list response — this echo carried the same // cleartext credentials straight back to the browser. "schedule": crate::secrets::to_redacted_json(&s), })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; } // Fleet scope. The SAME id goes to every node — a shared id means a later // edit or delete at fleet scope updates that one row everywhere, instead of // accumulating a near-duplicate schedule per node. let payload = serde_json::to_value(&schedule).unwrap_or(serde_json::json!({})); // Only write locally when THIS node is actually targeted. The local save // happens here rather than inside the fan-out (fleet_fanout_post takes an // already-computed result so blocking work stays off the async executor), // which means an unconditional save would write the schedule to the serving // node even when the operator's node picker excluded it. let self_targeted = body.target_nodes.is_empty() || body.target_nodes.contains(&state.cluster.self_id); let local = if self_targeted { let sched_for_local = schedule.clone(); let outcome = web::block(move || backup::save_schedule(sched_for_local).map(|s| s.id)) .await .unwrap_or_else(|e| Err(format!("local save panicked: {}", e))) .map(|id| serde_json::json!({ "ok": true, "id": id })); if let Err(e) = &outcome { tracing::warn!("backup fleet write: local save failed: {}", e); } Some(outcome) } else { None }; // An empty target list means every WolfStack node; a non-empty one is the // operator's node picker. Note fleet_fanout_post omits non-targeted nodes // entirely rather than reporting them skipped — they were never asked to // act, so they don't belong in the success/failure count either way. let targets = body.target_nodes.clone(); let results = fleet_fanout_post::( &state, "/api/backups/schedules/fleet-apply", payload, &targets, local, FANOUT_SLOW, ).await; let summary = fleet_result_summary(&results); let failed = summary["failed"].as_u64().unwrap_or(0); let succeeded = summary["succeeded"].as_u64().unwrap_or(0); let total = summary["total"].as_u64().unwrap_or(0); tracing::info!( "backup fleet write: schedule '{}' applied on {}/{} node(s)", schedule.name, succeeded, total, ); let mut payload = serde_json::json!({ "message": format!( "Schedule '{}' {} on {} of {} node(s)", schedule.name, if is_edit { "updated" } else { "created" }, succeeded, total, ), "schedule": crate::secrets::to_redacted_json(&schedule), "fleet": summary, }); if failed > 0 { // A partial fan-out is an ERROR, not a success with a footnote: the // nodes that missed it have no schedule and will never run a backup — // which is exactly how this went unnoticed in production. The GUI keys // its non-dismissing alert off this field. payload["error"] = serde_json::Value::String(format!( "{} of {} node(s) did not receive this schedule and will NOT back up: {}", failed, total, fleet_failed_nodes(&results).join("; "), )); return HttpResponse::MultiStatus().json(payload); } HttpResponse::Ok().json(payload) } /// POST /api/backups/schedules/{id}/run — run a scheduled backup on demand. pub async fn backup_schedule_run( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); // Starts the run and answers at once (202); the run itself can take hours. match web::block(move || backup::start_schedule_run(&id)).await { Ok(Ok(name)) => HttpResponse::Accepted().json(serde_json::json!({ "message": format!("Backup '{}' started. It runs in the background and its backups are listed when it finishes.", name), })), Ok(Err(backup::StartScheduleRunError::AlreadyRunning(e))) => HttpResponse::Conflict().json(serde_json::json!({ "error": e })), Ok(Err(backup::StartScheduleRunError::NotFound(e))) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/backups/schedules/{id}/enabled — enable/disable a schedule. pub async fn backup_schedule_toggle( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let enabled = body.enabled; match web::block(move || backup::set_schedule_enabled(&id, enabled)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// DELETE /api/backups/schedules/{id} — delete a schedule pub async fn backup_schedule_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match backup::delete_schedule(&path.into_inner()) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/backups/import — receive a backup from remote node pub async fn backup_import( req: HttpRequest, state: web::Data, body: web::Bytes, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let filename = query.get("filename") .map(|s| s.to_string()) .unwrap_or_else(|| format!("import-{}.tar.gz", chrono::Utc::now().timestamp())); match backup::import_backup(&body, &filename) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/backups/import?filename=X — remove a backup previously received /// via `backup_import`. The counterpart to import: called by a source node when /// the operator deletes a `Remote` backup, so the replicated copy on this node /// doesn't orphan. Auth is the same inter-node model as import (cluster secret /// via require_auth). pub async fn backup_import_delete( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let filename = match query.get("filename") { Some(f) if !f.trim().is_empty() => f.to_string(), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "filename query parameter is required" })), }; match web::block(move || backup::delete_imported_backup(&filename)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("task failed: {}", e) })), } } // ─── Proxmox Backup Server (PBS) API ─── /// GET /api/backups/pbs/status — check PBS connectivity pub async fn pbs_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let config = backup::load_pbs_config(); HttpResponse::Ok().json(backup::check_pbs_status(&config)) } /// GET /api/backups/pbs/snapshots — list all PBS snapshots, enriched with container details pub async fn pbs_snapshots( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let config = backup::load_pbs_config(); match backup::list_pbs_snapshots(&config) { Ok(snapshots) => { // Enrich ct/vm snapshots with local container/VM details let enriched = backup::enrich_pbs_snapshots(snapshots); HttpResponse::Ok().json(enriched) }, Err(e) => { eprintln!("PBS snapshot list failed: {}", e); HttpResponse::Ok().json(serde_json::json!([])) }, } } #[derive(Deserialize)] pub struct PbsRestoreRequest { pub snapshot: String, pub archive: String, #[serde(default = "default_pbs_target_dir")] pub target_dir: String, #[serde(default)] pub overwrite: bool, /// Restore the container under this name instead of the snapshot's /// original. Empty = keep the original. LXC only. #[serde(default)] pub new_name: String, /// Target Proxmox storage for the restored guest's disks (e.g. /// "local-lvm", "local-zfs"). Passed to `pct restore --storage` / /// `qm` restore. Empty = let Proxmox choose its default — but on hosts /// with no usable default for the guest type the restore fails, so the /// UI now offers a picker. Older nodes ignore this field. #[serde(default)] pub storage: String, } fn default_pbs_target_dir() -> String { "/var/lib/wolfstack/restored".to_string() } /// POST /api/backups/pbs/restore — restore a PBS snapshot (runs in background) pub async fn pbs_restore( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Check if a restore is already running (auto-expire after 30 min) { let mut progress = state.pbs_restore_progress.lock().unwrap(); let stale = progress.started_at .map(|t| t.elapsed().as_secs() > 1800) .unwrap_or(true); if progress.active && !progress.finished && !stale { return HttpResponse::Conflict().json(serde_json::json!({ "error": "A restore is already in progress", "snapshot": progress.snapshot, })); } // Clear stale or finished state if stale || progress.finished { *progress = PbsRestoreProgress::default(); } } let config = backup::load_pbs_config(); let snapshot = body.snapshot.clone(); let archive = body.archive.clone(); let target_dir = body.target_dir.clone(); let overwrite = body.overwrite; let new_name = body.new_name.clone(); let target_storage = body.storage.clone(); // Reset progress state { let mut progress = state.pbs_restore_progress.lock().unwrap(); *progress = PbsRestoreProgress { active: true, snapshot: snapshot.clone(), progress_text: "Starting restore...".to_string(), percentage: Some(0.0), finished: false, success: None, message: String::new(), started_at: Some(std::time::Instant::now()), }; } // Spawn background thread let state_clone = state.clone(); std::thread::spawn(move || { match backup::restore_from_pbs_with_progress(&config, &snapshot, &archive, &target_dir, |text, pct| { if let Ok(mut progress) = state_clone.pbs_restore_progress.lock() { progress.progress_text = text; progress.percentage = pct; } }, backup::PbsRestoreOptions { overwrite, new_name: &new_name, target_storage: &target_storage }) { Ok(msg) => { if let Ok(mut progress) = state_clone.pbs_restore_progress.lock() { progress.active = false; progress.finished = true; progress.success = Some(true); progress.message = msg; progress.percentage = Some(100.0); progress.progress_text = "Restore complete!".to_string(); } } Err(ref e) if e == "TARGET_EXISTS" => { if let Ok(mut progress) = state_clone.pbs_restore_progress.lock() { progress.active = false; progress.finished = true; progress.success = Some(false); progress.message = "TARGET_EXISTS".to_string(); progress.progress_text = "Target already has files from a previous restore".to_string(); } } Err(e) => { if let Ok(mut progress) = state_clone.pbs_restore_progress.lock() { progress.active = false; progress.finished = true; progress.success = Some(false); progress.message = e; progress.progress_text = "Restore failed".to_string(); } } } }); HttpResponse::Ok().json(serde_json::json!({ "status": "started", "message": "Restore started in background", })) } /// GET /api/backups/pbs/restore/progress — poll restore progress pub async fn pbs_restore_progress( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let progress = state.pbs_restore_progress.lock().unwrap().clone(); HttpResponse::Ok().json(progress) } /// GET /api/backups/pbs/config — get PBS configuration pub async fn pbs_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let config = backup::load_pbs_config(); // Return config without the token secret for security HttpResponse::Ok().json(serde_json::json!({ "pbs_server": config.pbs_server, "pbs_datastore": config.pbs_datastore, "pbs_user": config.pbs_user, "pbs_token_name": config.pbs_token_name, "pbs_fingerprint": config.pbs_fingerprint, "pbs_namespace": config.pbs_namespace, "pbs_rate_limit_mbps": config.pbs_rate_limit_mbps, "pbs_file_level": config.pbs_file_level, "has_token_secret": !config.pbs_token_secret.is_empty(), "has_password": !config.pbs_password.is_empty(), })) } #[derive(Deserialize)] pub struct PbsConfigRequest { pub pbs_server: String, pub pbs_datastore: String, pub pbs_user: String, #[serde(default)] pub pbs_token_name: String, #[serde(default)] pub pbs_token_secret: String, #[serde(default)] pub pbs_password: String, #[serde(default)] pub pbs_fingerprint: String, #[serde(default)] pub pbs_namespace: String, /// Upload cap in MB/s; 0 = unlimited. #[serde(default)] pub pbs_rate_limit_mbps: u32, /// Store content as native pxar (file-level) so PBS per-file restore works. #[serde(default)] pub pbs_file_level: bool, } // ─── Additional PBS destinations ────────────────────────────────── // // One PBS server can host several datastores with different backends // — PBS 4 added external S3 alongside local/NAS — and operators want // to choose per backup. These endpoints manage the extra destinations; // `backup::merge_pbs_secrets` binds a backup to one via // `pbs_target_id`. Empty fields on a destination inherit from the // primary connection, so a second datastore on the same server needs // only a name and a datastore name. /// Strip secrets from a destination before it goes over the wire. /// Mirrors `pbs_config_get`: the UI needs to know whether a credential /// is set, never what it is. fn pbs_target_public(t: &backup::PbsTarget) -> serde_json::Value { serde_json::json!({ "id": t.id, "name": t.name, "pbs_server": t.pbs_server, "pbs_datastore": t.pbs_datastore, "pbs_user": t.pbs_user, "pbs_token_name": t.pbs_token_name, "pbs_fingerprint": t.pbs_fingerprint, "pbs_namespace": t.pbs_namespace, "pbs_rate_limit_mbps": t.pbs_rate_limit_mbps, "pbs_file_level": t.pbs_file_level, "pbs_file_level_set": t.pbs_file_level_set, "has_token_secret": !t.pbs_token_secret.is_empty(), "has_password": !t.pbs_password.is_empty(), }) } /// GET /api/backups/pbs/targets — additional PBS destinations, with /// each one's effective (post-inheritance) server and datastore so the /// UI can show where a backup would actually land. pub async fn pbs_targets_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let targets = backup::load_pbs_targets(); let out: Vec = targets.iter().map(|t| { let resolved = backup::resolve_pbs_target(t); let mut v = pbs_target_public(t); v["effective_server"] = serde_json::json!(resolved.pbs_server); v["effective_datastore"] = serde_json::json!(resolved.pbs_datastore); v }).collect(); HttpResponse::Ok().json(out) } #[derive(Deserialize)] pub struct PbsTargetRequest { /// Empty on create; set when editing an existing destination. #[serde(default)] pub id: String, pub name: String, #[serde(default)] pub pbs_server: String, pub pbs_datastore: String, #[serde(default)] pub pbs_user: String, #[serde(default)] pub pbs_token_name: String, #[serde(default)] pub pbs_token_secret: String, #[serde(default)] pub pbs_password: String, #[serde(default)] pub pbs_fingerprint: String, #[serde(default)] pub pbs_namespace: String, /// Upload cap in MB/s; 0 inherits the primary connection's. #[serde(default)] pub pbs_rate_limit_mbps: u32, #[serde(default)] pub pbs_file_level: bool, #[serde(default)] pub pbs_file_level_set: bool, } /// Build a `PbsTarget` from a request, carrying forward secrets the /// operator didn't re-type (the form never receives them back, so an /// empty field means "unchanged", not "clear it"). fn pbs_target_from_request(body: &PbsTargetRequest, existing: Option<&backup::PbsTarget>) -> backup::PbsTarget { backup::PbsTarget { id: existing.map(|e| e.id.clone()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()), name: body.name.trim().to_string(), pbs_server: body.pbs_server.trim().to_string(), pbs_datastore: body.pbs_datastore.trim().to_string(), pbs_user: body.pbs_user.trim().to_string(), pbs_token_name: body.pbs_token_name.trim().to_string(), pbs_token_secret: if body.pbs_token_secret.is_empty() { existing.map(|e| e.pbs_token_secret.clone()).unwrap_or_default() } else { body.pbs_token_secret.clone() }, pbs_password: if body.pbs_password.is_empty() { existing.map(|e| e.pbs_password.clone()).unwrap_or_default() } else { body.pbs_password.clone() }, pbs_fingerprint: body.pbs_fingerprint.trim().to_string(), pbs_namespace: body.pbs_namespace.trim().to_string(), pbs_rate_limit_mbps: body.pbs_rate_limit_mbps, pbs_file_level: body.pbs_file_level, pbs_file_level_set: body.pbs_file_level_set, } } /// POST /api/backups/pbs/targets — create or update a destination. pub async fn pbs_targets_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); if body.name.trim().is_empty() { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "Give this destination a name" })); } if body.pbs_datastore.trim().is_empty() { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "Datastore is required — it's what makes this a separate destination" })); } let mut targets = backup::load_pbs_targets(); let existing = targets.iter().find(|t| t.id == body.id).cloned(); if !body.id.is_empty() && existing.is_none() { return HttpResponse::NotFound() .json(serde_json::json!({ "error": "That PBS destination no longer exists" })); } let target = pbs_target_from_request(&body, existing.as_ref()); match targets.iter_mut().find(|t| t.id == target.id) { Some(slot) => *slot = target.clone(), None => targets.push(target.clone()), } if let Err(e) = backup::save_pbs_targets(&targets) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } let resolved = backup::resolve_pbs_target(&target); tracing::info!( "backup: saved PBS destination '{}' -> {}:{}", target.name, resolved.pbs_server, resolved.pbs_datastore, ); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "target": pbs_target_public(&target), "effective_server": resolved.pbs_server, "effective_datastore": resolved.pbs_datastore, })) } /// POST /api/backups/pbs/targets/test — prove a destination works. /// Accepts an unsaved destination so the operator can verify a /// datastore name BEFORE committing a schedule to it. pub async fn pbs_targets_test( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let body = body.into_inner(); let existing = if body.id.is_empty() { None } else { backup::find_pbs_target(&body.id) }; let target = pbs_target_from_request(&body, existing.as_ref()); let resolved = backup::resolve_pbs_target(&target); // proxmox-backup-client is a subprocess — keep it off the executor. let result = tokio::task::spawn_blocking(move || backup::test_pbs_target(&target)).await; match result { Ok(Ok(count)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "server": resolved.pbs_server, "datastore": resolved.pbs_datastore, "snapshot_count": count, })), Ok(Err(e)) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "server": resolved.pbs_server, "datastore": resolved.pbs_datastore, "error": e, })), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("PBS test task panicked: {}", e) })), } } /// DELETE /api/backups/pbs/targets/{id} — remove a destination. /// /// Refuses while a schedule still points at it: deleting anyway would /// leave that schedule failing every night with nothing to explain why. pub async fn pbs_targets_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let users: Vec = backup::list_schedules().into_iter() .filter(|s| s.storage.pbs_target_id == id) .map(|s| s.name) .collect(); if !users.is_empty() { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!( "{} schedule(s) still back up to this destination: {}. Point them somewhere else first.", users.len(), users.join(", "), ), })); } let mut targets = backup::load_pbs_targets(); let before = targets.len(); targets.retain(|t| t.id != id); if targets.len() == before { return HttpResponse::NotFound() .json(serde_json::json!({ "error": "That PBS destination no longer exists" })); } if let Err(e) = backup::save_pbs_targets(&targets) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } /// GET /api/backups/pbs/config/full — return PBS config INCLUDING secrets (for node-to-node copy) pub async fn pbs_config_get_full( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let config = backup::load_pbs_config(); HttpResponse::Ok().json(serde_json::json!({ "pbs_server": config.pbs_server, "pbs_datastore": config.pbs_datastore, "pbs_user": config.pbs_user, "pbs_token_name": config.pbs_token_name, "pbs_token_secret": config.pbs_token_secret, "pbs_password": config.pbs_password, "pbs_fingerprint": config.pbs_fingerprint, "pbs_namespace": config.pbs_namespace, "pbs_rate_limit_mbps": config.pbs_rate_limit_mbps, "pbs_file_level": config.pbs_file_level, })) } /// POST /api/backups/pbs/config — save PBS configuration pub async fn pbs_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Preserve existing secrets if the user didn't re-enter them let existing = backup::load_pbs_config(); let storage = backup::BackupStorage { storage_type: backup::StorageType::Pbs, pbs_server: body.pbs_server.clone(), pbs_datastore: body.pbs_datastore.clone(), pbs_user: body.pbs_user.clone(), pbs_token_name: body.pbs_token_name.clone(), pbs_token_secret: if body.pbs_token_secret.is_empty() { existing.pbs_token_secret } else { body.pbs_token_secret.clone() }, pbs_password: if body.pbs_password.is_empty() { existing.pbs_password } else { body.pbs_password.clone() }, // Store the fingerprint in the canonical colon-separated form so it // round-trips correctly to proxmox-backup-client and shows cleanly in // the UI, whether the operator pasted it with or without colons. pbs_fingerprint: backup::format_pbs_fingerprint(&body.pbs_fingerprint), pbs_namespace: body.pbs_namespace.clone(), pbs_rate_limit_mbps: body.pbs_rate_limit_mbps, pbs_file_level: body.pbs_file_level, ..backup::BackupStorage::default() }; match backup::save_pbs_config(&storage) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "PBS configuration saved", })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } // ─── Wolfram Memory Compression ─── /// GET /api/wolfram/status — check if wolfram is installed and read stats pub async fn wolfram_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let installed = std::path::Path::new("/usr/local/bin/wolfram").exists(); let service_active = Command::new("systemctl") .args(["is-active", "wolfram"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "active") .unwrap_or(false); let service_enabled = Command::new("systemctl") .args(["is-enabled", "wolfram"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "enabled") .unwrap_or(false); let version = if installed { Command::new("/usr/local/bin/wolfram") .arg("--version") .output() .ok() .and_then(|o| { let s = String::from_utf8_lossy(&o.stdout).trim().to_string(); // Output is typically "wolfram X.Y.Z" — extract version s.split_whitespace().last().map(|v| v.to_string()) }) } else { None }; let stats: Option = if service_active { std::fs::read_to_string("/var/lib/wolfram/stats.json") .ok() .and_then(|s| serde_json::from_str(&s).ok()) } else { None }; HttpResponse::Ok().json(serde_json::json!({ "installed": installed, "active": service_active, "enabled": service_enabled, "version": version, "stats": stats, })) } /// POST /api/wolfram/install — install wolfram via the install script pub async fn wolfram_install( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(|| { let output = Command::new("sh") .args(["-c", "curl -fsSL https://raw.githubusercontent.com/intelligentwolf/wolfram/master/install.sh | sh"]) .output(); match output { Ok(o) => { let stdout = String::from_utf8_lossy(&o.stdout).to_string(); let stderr = String::from_utf8_lossy(&o.stderr).to_string(); if o.status.success() { Ok(format!("{}\n{}", stdout, stderr)) } else { Err(format!("Install failed (exit {}): {}\n{}", o.status.code().unwrap_or(-1), stdout, stderr)) } } Err(e) => Err(format!("Failed to run installer: {}", e)), } }).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } /// POST /api/wolfram/uninstall — remove wolfram pub async fn wolfram_uninstall( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(|| { // Stop service, disable, remove binary and service file let _ = Command::new("systemctl").args(["stop", "wolfram"]).output(); let _ = Command::new("systemctl").args(["disable", "wolfram"]).output(); let _ = std::fs::remove_file("/usr/local/bin/wolfram"); let _ = std::fs::remove_file("/etc/systemd/system/wolfram.service"); let _ = Command::new("systemctl").arg("daemon-reload").output(); Ok::<_, String>("Wolfram uninstalled".to_string()) }).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct WolframActionRequest { pub action: String, } /// POST /api/wolfram/action — start/stop/restart wolfram service pub async fn wolfram_action( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let action = match body.action.as_str() { "start" | "stop" | "restart" | "enable" | "disable" => body.action.as_str(), _ => return HttpResponse::BadRequest().json(serde_json::json!({"error": "Invalid action"})), }; match Command::new("systemctl").args([action, "wolfram"]).output() { Ok(o) if o.status.success() => { HttpResponse::Ok().json(serde_json::json!({"ok": true})) } Ok(o) => { let err = String::from_utf8_lossy(&o.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": err})) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } /// GET /api/wolfram/config — read /etc/wolfram/config.toml pub async fn wolfram_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let content = std::fs::read_to_string("/etc/wolfram/config.toml").unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({"config": content})) } #[derive(Deserialize)] pub struct WolframConfigSaveRequest { pub config: String, } /// POST /api/wolfram/config — write /etc/wolfram/config.toml pub async fn wolfram_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let _ = std::fs::create_dir_all("/etc/wolfram"); match std::fs::write("/etc/wolfram/config.toml", &body.config) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({"ok": true})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } // ─── Ceph Cluster API ─── /// GET /api/ceph/status — full cluster status pub async fn ceph_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // get_cluster_status shells out to ~10 ceph commands — keep it off the // actix worker thread. match web::block(crate::ceph::get_cluster_status).await { Ok(status) => HttpResponse::Ok().json(status), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// GET /api/ceph/install-status — check what ceph components are installed pub async fn ceph_install_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Runs a handful of `which` probes — keep them off the actix worker thread. match web::block(crate::ceph::get_install_status).await { Ok(status) => HttpResponse::Ok().json(status), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// GET /api/ceph/devices — list available devices for OSD creation pub async fn ceph_devices( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::get_available_devices() { Ok(devices) => HttpResponse::Ok().json(devices), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// POST /api/ceph/install — install ceph packages pub async fn ceph_install( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::ceph::install_ceph).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephBootstrapRequest { #[serde(default)] pub cluster_name: String, pub public_network: String, pub mon_ip: String, } /// POST /api/ceph/bootstrap — bootstrap a new cluster pub async fn ceph_bootstrap( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::bootstrap_cluster(&body.cluster_name, &body.public_network, &body.mon_ip) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// GET /api/ceph/cluster-bundle — export this (bootstrapped) node's config + /// keyrings so another node can JOIN the cluster. Authed by a logged-in operator /// OR the cluster secret (the joining node's backend fetches it inter-node). The /// bundle carries the client.admin keyring, so it only ever goes to an /// authenticated caller. pub async fn ceph_cluster_bundle(req: HttpRequest, state: web::Data) -> HttpResponse { if require_auth(&req, &state).is_err() && require_cluster_auth(&req, &state).is_err() { return HttpResponse::Forbidden().json(serde_json::json!({"error": "authentication required"})); } match web::block(crate::ceph::export_join_bundle).await { Ok(Ok(bundle)) => HttpResponse::Ok().json(bundle), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("export failed: {}", e)})), } } #[derive(Deserialize)] pub struct CephJoinRequest { pub source_node_id: String, } /// POST /api/ceph/join — join the cluster that `source_node_id` belongs to by /// fetching its config + keyrings and installing them locally. Operator-authed; /// the node then contributes via the existing "Add OSD" flow. pub async fn ceph_join(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let node = match state.cluster.get_node(&body.source_node_id) { Some(n) => n, None => return HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": "source node not found in cluster"})), }; if node.is_self { return HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": "select a different node — that one is this node"})); } // Fetch the join bundle from the source node (inter-node secret auth). let urls = build_node_urls(&node.address, node.port, "/api/ceph/cluster-bundle"); let client = &*API_HTTP_CLIENT; let mut bundle: Option = None; let mut last_err = String::from("no URL reachable"); for url in &urls { match client.get(url) .timeout(std::time::Duration::from_secs(20)) .peer_auth(state.cluster_secret.clone()) .send().await { Ok(resp) if resp.status().is_success() => match resp.json::().await { Ok(b) => { bundle = Some(b); break; } Err(e) => last_err = format!("parse bundle from source: {}", e), }, Ok(resp) => { let code = resp.status(); last_err = format!("source returned {}: {}", code, resp.text().await.unwrap_or_default()); } Err(e) => last_err = format!("reach source: {}", e), } } let bundle = match bundle { Some(b) => b, None => return HttpResponse::BadGateway().json(serde_json::json!({"ok": false, "error": format!("couldn't fetch the cluster config from the source node — {}", last_err)})), }; match web::block(move || crate::ceph::join_cluster(&bundle)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("join task failed: {}", e)})), } } #[derive(Deserialize)] pub struct CephCreatePoolRequest { pub name: String, #[serde(default)] pub pg_num: u32, #[serde(default = "default_pool_type")] pub pool_type: String, #[serde(default)] pub size: Option, #[serde(default)] pub crush_rule: Option, #[serde(default)] pub application: Option, } fn default_pool_type() -> String { "replicated".to_string() } /// POST /api/ceph/pools — create a pool pub async fn ceph_create_pool( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::create_pool(&body.name, body.pg_num, &body.pool_type, body.size, body.crush_rule.as_deref(), body.application.as_deref()) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// DELETE /api/ceph/pools/{name} — delete a pool pub async fn ceph_delete_pool( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool_name = path.into_inner(); match crate::ceph::delete_pool(&pool_name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } #[derive(Deserialize)] pub struct CephSetPoolOptionRequest { pub key: String, pub value: String, } /// PUT /api/ceph/pools/{name} — set pool options pub async fn ceph_set_pool_option( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool_name = path.into_inner(); match crate::ceph::set_pool_option(&pool_name, &body.key, &body.value) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } #[derive(Deserialize)] pub struct CephAddOsdRequest { pub device: String, } /// POST /api/ceph/osds — add an OSD pub async fn ceph_add_osd( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::add_osd(&body.device) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// DELETE /api/ceph/osds/{id} — remove an OSD pub async fn ceph_remove_osd( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let osd_id = path.into_inner(); match crate::ceph::remove_osd(osd_id) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } #[derive(Deserialize)] pub struct CephOsdActionRequest { pub action: String, #[serde(default)] pub weight: Option, } /// POST /api/ceph/osds/{id}/action — mark in/out, reweight pub async fn ceph_osd_action( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let osd_id = path.into_inner(); let weight = body.weight; let action = body.action.clone(); let result = web::block(move || match action.as_str() { "in" => crate::ceph::set_osd_in(osd_id, true), "out" => crate::ceph::set_osd_in(osd_id, false), "down" => crate::ceph::mark_osd_down(osd_id), "scrub" => crate::ceph::osd_scrub(osd_id, false), "deep-scrub" => crate::ceph::osd_scrub(osd_id, true), "reweight" => { let w = weight.unwrap_or(1.0); crate::ceph::reweight_osd(osd_id, w) }, other => Err(format!("Unknown action: {}", other)), }).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephCreateFsRequest { pub name: String, pub metadata_pool: String, pub data_pool: String, } /// POST /api/ceph/fs — create a CephFS pub async fn ceph_create_fs( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::create_filesystem(&body.name, &body.metadata_pool, &body.data_pool) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// DELETE /api/ceph/fs/{name} — remove a CephFS pub async fn ceph_delete_fs( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let fs_name = path.into_inner(); match crate::ceph::remove_filesystem(&fs_name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// GET /api/ceph/rbd/{pool} — list RBD images pub async fn ceph_list_rbd( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = path.into_inner(); match crate::ceph::list_rbd_images(&pool) { Ok(images) => HttpResponse::Ok().json(images), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct CephCreateRbdRequest { pub pool: String, pub name: String, pub size_mb: u64, } /// POST /api/ceph/rbd — create RBD image pub async fn ceph_create_rbd( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::ceph::create_rbd_image(&body.pool, &body.name, body.size_mb) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } /// DELETE /api/ceph/rbd/{pool}/{image} — delete RBD image pub async fn ceph_delete_rbd( req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (pool, image) = path.into_inner(); match crate::ceph::delete_rbd_image(&pool, &image) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), } } // ─── Ceph Maintenance / Repair / HA API ─── #[derive(Deserialize)] pub struct CephFlagRequest { pub flag: String, pub enable: bool, } /// POST /api/ceph/flags — set/clear an operational cluster flag (noout, …) pub async fn ceph_set_flag( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (flag, enable) = (body.flag.clone(), body.enable); match web::block(move || crate::ceph::set_cluster_flag(&flag, enable)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephPgActionRequest { pub pgid: String, pub action: String, } /// POST /api/ceph/pg-action — scrub/deep-scrub/repair a placement group pub async fn ceph_pg_action( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (pgid, action) = (body.pgid.clone(), body.action.clone()); match web::block(move || crate::ceph::pg_action(&pgid, &action)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephBalancerRequest { pub enable: bool, } /// POST /api/ceph/balancer — turn the automatic PG balancer on/off pub async fn ceph_balancer( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let enable = body.enable; match web::block(move || crate::ceph::set_balancer(enable)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephDaemonRequest { pub kind: String, pub id: String, pub action: String, } /// POST /api/ceph/daemon — start/stop/restart a ceph daemon on this node pub async fn ceph_daemon_control( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let (kind, id, action) = (body.kind.clone(), body.id.clone(), body.action.clone()); match web::block(move || crate::ceph::daemon_control(&kind, &id, &action)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CephAddMonRequest { pub mon_ip: String, } /// POST /api/ceph/monitors — promote this node to also run a monitor (HA) pub async fn ceph_add_monitor( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let mon_ip = body.mon_ip.clone(); match web::block(move || crate::ceph::add_monitor(&mon_ip)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } /// POST /api/ceph/managers — add a manager (standby) on this node (HA) pub async fn ceph_add_manager( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::ceph::add_manager).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } // ─── GlusterFS API ─── // // Cluster-scoped Gluster management surfaced in the Storage area. Gluster is // inherently cluster-wide (any peer manages the whole trusted pool), so these // run against the targeted node (the frontend node-proxy picks the node); from // there the whole pool is visible/manageable. Mirrors the Ceph handler idiom: // every call wraps the shell-out in web::block. #[derive(Deserialize)] pub struct GlusterBootstrapRequest { #[serde(default)] pub cluster_name: String, } #[derive(Deserialize)] pub struct GlusterPeerRequest { pub host: String, } #[derive(Deserialize)] pub struct GlusterCreateVolumeRequest { pub name: String, #[serde(default)] pub vol_type: String, #[serde(default)] pub count: u32, #[serde(default)] pub bricks: Vec, } #[derive(Deserialize)] pub struct GlusterOptionRequest { pub key: String, pub value: String, } #[derive(Deserialize)] pub struct GlusterBricksRequest { pub bricks: Vec, } /// GET /api/gluster/status — peers, volumes, bricks, heal rollup pub async fn gluster_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::gluster::get_status).await { Ok(status) => HttpResponse::Ok().json(status), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// GET /api/gluster/install-status — installed / running / importable pub async fn gluster_install_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::gluster::get_install_status).await { Ok(v) => HttpResponse::Ok().json(v), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// GET /api/gluster/devices — block devices (lsblk) to help pick brick paths pub async fn gluster_devices(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::gluster::available_devices).await { Ok(Ok(v)) => HttpResponse::Ok().json(v), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": format!("{}", e)})), } } /// POST /api/gluster/install — install glusterfs + start glusterd pub async fn gluster_install(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } gluster_result(web::block(crate::gluster::install).await) } /// POST /api/gluster/bootstrap — start a fresh pool + record the cluster label pub async fn gluster_bootstrap( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = body.cluster_name.clone(); gluster_result(web::block(move || crate::gluster::bootstrap(&name)).await) } /// POST /api/gluster/import — adopt an already-running glusterd (existing pool) pub async fn gluster_import( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = body.cluster_name.clone(); match web::block(move || crate::gluster::import_existing(&name)).await { Ok(Ok(status)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "status": status})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } /// POST /api/gluster/peers — probe a peer into the pool pub async fn gluster_add_peer( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let host = body.host.clone(); gluster_result(web::block(move || crate::gluster::add_peer(&host)).await) } /// DELETE /api/gluster/peers/{host} — detach a peer pub async fn gluster_remove_peer( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let host = path.into_inner(); gluster_result(web::block(move || crate::gluster::remove_peer(&host)).await) } /// POST /api/gluster/volumes — create a volume pub async fn gluster_create_volume( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); gluster_result(web::block(move || crate::gluster::create_volume(&b.name, &b.vol_type, b.count, &b.bricks)).await) } /// DELETE /api/gluster/volumes/{name} — stop (if needed) + delete a volume pub async fn gluster_delete_volume( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); gluster_result(web::block(move || crate::gluster::delete_volume(&name)).await) } /// POST /api/gluster/volumes/{name}/start pub async fn gluster_start_volume( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); gluster_result(web::block(move || crate::gluster::start_volume(&name)).await) } /// POST /api/gluster/volumes/{name}/stop pub async fn gluster_stop_volume( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); gluster_result(web::block(move || crate::gluster::stop_volume(&name)).await) } /// POST /api/gluster/volumes/{name}/heal — trigger a full self-heal pub async fn gluster_heal_volume( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); gluster_result(web::block(move || crate::gluster::heal_volume(&name)).await) } /// PUT /api/gluster/volumes/{name} — set a volume option pub async fn gluster_set_option( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let (key, value) = (body.key.clone(), body.value.clone()); gluster_result(web::block(move || crate::gluster::set_volume_option(&name, &key, &value)).await) } /// POST /api/gluster/volumes/{name}/bricks — add bricks pub async fn gluster_add_brick( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let bricks = body.bricks.clone(); gluster_result(web::block(move || crate::gluster::add_brick(&name, &bricks)).await) } /// POST /api/gluster/volumes/{name}/remove-brick — remove bricks (committed) pub async fn gluster_remove_brick( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let bricks = body.bricks.clone(); gluster_result(web::block(move || crate::gluster::remove_brick(&name, &bricks)).await) } /// Shared {ok,message}/{ok,error} responder for the gluster action handlers. fn gluster_result(r: Result, actix_web::error::BlockingError>) -> HttpResponse { match r { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } // ─── Storage Manager API ─── /// GET /api/storage/mounts — list all storage mounts with live status pub async fn storage_list_mounts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Secrets are redacted before the mounts reach the browser: the page // renders a name/bucket table and never needs the S3 secret key or the // SMB password, but the raw structs carried both into the DOM of every // admin session (and into any browser extension or error reporter that // reads a response body). The sentinel is the same one the PUT handler // already treats as "keep the stored value", so an edit round-trips. HttpResponse::Ok().json(storage::list_mounts_redacted()) } /// GET /api/storage/available — list mounted storage suitable for container attachment pub async fn storage_available_mounts( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(storage::available_mounts()) } #[derive(Deserialize)] pub struct CreateMountRequest { pub name: String, #[serde(rename = "type")] pub mount_type: storage::MountType, #[serde(default)] pub source: String, #[serde(default)] pub mount_point: String, #[serde(default)] pub global: bool, #[serde(default)] pub auto_mount: bool, #[serde(default)] pub s3_config: Option, /// Id of a saved S3 remote to take the credentials from, instead of /// sending them in `s3_config`. Set by the "Saved credentials" picker so /// no secret ever travels to the browser and back. #[serde(default)] pub s3_remote: Option, /// Bucket to mount when creating from a saved remote. #[serde(default)] pub s3_bucket: Option, #[serde(default)] pub nfs_options: Option, #[serde(default)] pub smb_options: Option, #[serde(default)] pub smb_config: Option, #[serde(default = "default_do_mount")] pub do_mount: bool, } fn default_do_mount() -> bool { true } /// POST /api/storage/mounts — create a new storage mount pub async fn storage_create_mount( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // A saved remote supplies the credentials, endpoint, region and provider; // the operator only chooses which bucket on it to mount. let (s3_config, source) = match body.s3_remote.as_deref() { Some(remote_id) if !remote_id.is_empty() => { let bucket = body.s3_bucket.clone().unwrap_or_default(); if bucket.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Pick a bucket for this mount" })); } match storage::s3_config_from_remote(remote_id, bucket.trim()) { Ok(cfg) => { let src = format!("s3:{}", cfg.bucket); (Some(cfg), src) } Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } _ => (body.s3_config.clone(), body.source.clone()), }; let mount = storage::StorageMount { id: String::new(), name: body.name.clone(), mount_type: body.mount_type.clone(), source, mount_point: body.mount_point.clone(), enabled: true, global: body.global, auto_mount: body.auto_mount, s3_config, nfs_options: body.nfs_options.clone(), smb_options: body.smb_options.clone(), smb_config: body.smb_config.clone(), status: "unmounted".to_string(), error_message: None, created_at: String::new(), }; let do_mount = body.do_mount; // Run on blocking threadpool — mount_s3_via_rust_s3 creates a nested tokio runtime // which panics if called directly from an async context let result = web::block(move || storage::create_mount(mount, do_mount)).await; match result { Ok(Ok(created)) => { // If global, sync to cluster nodes if created.global { let _ = sync_mount_to_cluster(&state, &created).await; } HttpResponse::Ok().json(created) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } /// GET /api/fs/browse?path=...&show_hidden=... /// /// Lists immediate children of a directory for the operator-facing /// file picker modal. Auth-gated (admin session cookie). Excludes /// known noisy pseudo-filesystems (`/proc`, `/sys`, `/dev`, `/run`) /// because those produce thousands of useless rows in a click-driven /// picker — operators with a real reason to inspect them have shell /// access already. /// /// The endpoint never reads file contents and never recurses; the /// per-call cost is bounded by the number of immediate children. /// Symlinks are reported as their own kind without following — the /// caller decides whether to traverse. /// /// Errors (path doesn't exist, permission denied) are returned as /// HTTP 200 with a populated `error` field rather than HTTP 4xx, so /// the frontend can show the message inline in the picker without /// translating status codes. Auth failures still return 401. #[derive(Deserialize)] pub struct FsBrowseQuery { pub path: Option, #[serde(default)] pub show_hidden: bool, } #[derive(Serialize)] pub struct FsBrowseEntry { pub name: String, pub kind: String, // "dir" | "file" | "symlink" | "other" pub size: Option, // bytes; None for non-files pub modified: Option, // RFC3339 UTC } #[derive(Serialize)] pub struct FsBrowseResponse { pub path: String, pub parent: Option, pub entries: Vec, pub error: Option, } pub async fn fs_browse( req: HttpRequest, state: web::Data, q: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let path_raw = q.path.clone().unwrap_or_else(|| "/".to_string()); let path = std::path::PathBuf::from(&path_raw); // Canonicalize so a request like `/etc/../etc/passwd` collapses // to `/etc/passwd` and a symlink target is resolved before we // run the noise-filter check. If the path doesn't exist the // operator gets a clear "Cannot access" message rather than an // empty listing. let canon = match std::fs::canonicalize(&path) { Ok(p) => p, Err(e) => return HttpResponse::Ok().json(FsBrowseResponse { path: path_raw, parent: None, entries: vec![], error: Some(format!("Cannot access: {}", e)), }), }; const DENIED_ROOTS: &[&str] = &["/proc", "/sys", "/dev", "/run"]; let canon_str = canon.to_string_lossy().to_string(); if DENIED_ROOTS.iter().any(|r| canon_str == *r || canon_str.starts_with(&format!("{}/", r))) { return HttpResponse::Ok().json(FsBrowseResponse { path: canon_str, parent: None, entries: vec![], error: Some("Path is on a pseudo-filesystem (/proc, /sys, /dev, /run) — not browsable".into()), }); } let dir_iter = match std::fs::read_dir(&canon) { Ok(d) => d, Err(e) => return HttpResponse::Ok().json(FsBrowseResponse { path: canon_str, parent: None, entries: vec![], error: Some(format!("Cannot list: {}", e)), }), }; let mut entries: Vec = Vec::new(); for ent in dir_iter.flatten() { let name = ent.file_name().to_string_lossy().to_string(); if !q.show_hidden && name.starts_with('.') { continue; } // Use symlink_metadata so a symlink reports as `symlink` // rather than the kind of its target — operators picking // a path want to know what's actually on disk. let meta = ent.metadata().ok(); let kind = if let Some(m) = &meta { if m.is_dir() { "dir" } else if m.is_file() { "file" } else if m.file_type().is_symlink() { "symlink" } else { "other" } } else { "other" }; let size = meta.as_ref().filter(|m| m.is_file()).map(|m| m.len()); let modified = meta.as_ref().and_then(|m| m.modified().ok()) .map(|t| { let dt: chrono::DateTime = t.into(); dt.to_rfc3339() }); entries.push(FsBrowseEntry { name, kind: kind.into(), size, modified }); } // Dirs first, then files; alphabetical case-insensitive within // each group. Matches the behaviour every other file picker // operators have used (Finder, Explorer, GTK, KDE). entries.sort_by(|a, b| { let kind_order = (a.kind != "dir").cmp(&(b.kind != "dir")); if kind_order != std::cmp::Ordering::Equal { return kind_order; } a.name.to_lowercase().cmp(&b.name.to_lowercase()) }); let parent = canon.parent().map(|p| p.to_string_lossy().to_string()); HttpResponse::Ok().json(FsBrowseResponse { path: canon_str, parent, entries, error: None, }) } /// PUT /api/storage/mounts/{id} — update a mount pub async fn storage_update_mount( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match storage::update_mount(&id, body.into_inner()) { Ok(updated) => HttpResponse::Ok().json(updated), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/storage/mounts/{id} — remove a mount pub async fn storage_remove_mount( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match storage::remove_mount(&id) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/storage/mounts/{id}/duplicate — clone a mount entry pub async fn storage_duplicate_mount( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); match storage::duplicate_mount(&id) { Ok(dup) => HttpResponse::Ok().json(dup), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/storage/mounts/{id}/mount — mount a storage entry pub async fn storage_do_mount( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); // Run on blocking threadpool — mount_s3_via_rust_s3 creates a nested tokio runtime // which panics if called directly from an async context let result = web::block(move || storage::mount_storage(&id)).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } /// POST /api/storage/mounts/{id}/unmount — unmount a storage entry pub async fn storage_do_unmount( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let result = web::block(move || storage::unmount_storage(&id)).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } #[derive(Deserialize)] pub struct ImportRcloneRequest { pub config: String, } /// POST /api/storage/import-rclone — import S3 remotes from rclone.conf content /// /// Imports REMOTES (reusable credential sets), not mounts: an rclone remote /// carries no bucket, and an S3 mount without a bucket can never mount, so /// the previous mount-per-remote import only ever produced broken entries. pub async fn storage_import_rclone( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match storage::import_rclone_remotes(&body.config) { Ok(names) => HttpResponse::Ok().json(serde_json::json!({ "message": format!( "Imported {} S3 remote{}: {}. Pick them under Add Mount \u{2192} S3 \u{2192} Saved credentials.", names.len(), if names.len() == 1 { "" } else { "s" }, names.join(", ") ), "remotes": names })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/storage/s3-remotes — saved S3 credential sets, WITHOUT secrets pub async fn storage_list_s3_remotes( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(storage::list_s3_remote_infos()) } #[derive(Deserialize)] pub struct SaveS3RemoteRequest { pub name: String, #[serde(default)] pub provider: String, #[serde(default)] pub endpoint: String, #[serde(default)] pub region: String, /// Blank when updating an existing remote = keep the stored key (the /// browser only ever sees a masked hint, so the edit form cannot /// round-trip it). #[serde(default)] pub access_key_id: String, /// Blank when updating an existing remote = keep the stored secret. #[serde(default)] pub secret_access_key: String, } #[derive(Deserialize)] pub struct TestS3RemoteRequest { /// Test a SAVED remote by id — mutually exclusive with the inline fields. #[serde(default)] pub id: String, /// Inline fields from a form. Endpoint/region/provider are tested as /// typed; blank credential fields resolve via `credentials_from`. #[serde(default)] pub provider: String, #[serde(default)] pub endpoint: String, #[serde(default)] pub region: String, #[serde(default)] pub access_key_id: String, #[serde(default)] pub secret_access_key: String, /// Remote id (`wolfstack:name` or `mount:id`) whose STORED credentials /// fill any blank credential field — the edit-form case, where the /// browser never held the secret (and only a masked key hint) but the /// operator may have changed endpoint/region and wants them tested. #[serde(default)] pub credentials_from: String, /// Optional bucket for the scoped-key fallback probe. #[serde(default)] pub bucket: String, } /// POST /api/storage/s3-remotes/test — verify a credential set actually /// works against its endpoint, without saving or mounting anything. pub async fn storage_test_s3_remote( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let r = body.into_inner(); let remote = if !r.id.is_empty() { match storage::find_s3_remote(&r.id) { Some(remote) => remote, None => { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": format!("Remote '{}' not found", r.id) })) } } } else { let mut remote = storage::S3Remote { id: String::new(), name: String::new(), provider: if r.provider.is_empty() { "AWS".to_string() } else { r.provider.clone() }, endpoint: r.endpoint.clone(), region: r.region.clone(), access_key_id: r.access_key_id.trim().to_string(), secret_access_key: r.secret_access_key.clone(), origin: String::new(), }; // Edit-form case: blank credential fields resolve from the named // stored remote/mount — the browser never held the secret, but the // endpoint/region as typed still get tested. if (remote.access_key_id.is_empty() || remote.secret_access_key.is_empty()) && !r.credentials_from.is_empty() && let Some(stored) = storage::find_s3_remote(&r.credentials_from) { if remote.access_key_id.is_empty() { remote.access_key_id = stored.access_key_id; } if remote.secret_access_key.is_empty() { remote.secret_access_key = stored.secret_access_key; } } if remote.access_key_id.is_empty() || remote.secret_access_key.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Access Key ID and Secret Access Key are required to test (or pick a saved credential set)" })); } remote }; let bucket = r.bucket.clone(); // web::block — test_s3_connection builds its own current-thread runtime, // which panics if constructed inside the actix worker's runtime. let result = web::block(move || storage::test_s3_connection(&remote, &bucket)).await; match result { Ok(outcome) => HttpResponse::Ok().json(outcome), Err(e) => HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct S3BucketOpRequest { pub id: String, pub bucket: String, } /// POST /api/storage/s3-remotes/buckets — create a bucket on a saved remote pub async fn storage_create_s3_bucket( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let r = body.into_inner(); let (id, bucket) = (r.id, r.bucket); let bucket_for_msg = bucket.clone(); // web::block — create_remote_bucket builds its own current-thread runtime. let result = web::block(move || storage::create_remote_bucket(&id, &bucket)).await; match result { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Bucket “{}” created", bucket_for_msg) })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/storage/s3-remotes/buckets/delete — delete an EMPTY bucket. /// Body-style like the remote delete: ids contain ':' so path segments /// don't fit them. pub async fn storage_delete_s3_bucket( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let r = body.into_inner(); let (id, bucket) = (r.id, r.bucket); let bucket_for_msg = bucket.clone(); let result = web::block(move || storage::delete_remote_bucket(&id, &bucket)).await; match result { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Bucket “{}” deleted", bucket_for_msg) })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── S3 bucket-sync jobs ─── /// GET /api/storage/s3-sync — every job, with a derived `running` flag pub async fn storage_list_sync_jobs( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let config = storage::s3_sync::load(); let jobs: Vec = config.jobs.iter().map(|j| { let mut v = serde_json::to_value(j).unwrap_or_else(|_| serde_json::json!({})); if let Some(obj) = v.as_object_mut() { obj.insert("running".into(), serde_json::json!(storage::s3_sync::is_running(&j.id))); } v }).collect(); HttpResponse::Ok().json(jobs) } #[derive(Deserialize)] pub struct SaveSyncJobRequest { #[serde(flatten)] pub job: storage::s3_sync::SyncJob, /// Required true when mode == sync — the UI's typed confirmation. #[serde(default)] pub confirm_sync: bool, } /// POST /api/storage/s3-sync — create or update a job pub async fn storage_save_sync_job( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let r = body.into_inner(); match storage::s3_sync::save_job(r.job, r.confirm_sync) { Ok(job) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Sync job “{}” saved", job.name), "id": job.id, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct SyncJobIdRequest { pub id: String, } /// POST /api/storage/s3-sync/delete pub async fn storage_delete_sync_job( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match storage::s3_sync::delete_job(&body.id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": "Sync job deleted" })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct SyncJobToggleRequest { pub id: String, pub enabled: bool, } /// POST /api/storage/s3-sync/toggle — pause/resume scheduling pub async fn storage_toggle_sync_job( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match storage::s3_sync::set_enabled(&body.id, body.enabled) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": if body.enabled { "Sync job enabled" } else { "Sync job paused" } })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/storage/s3-sync/run — start a pass NOW, in the background. /// Returns immediately; progress lands in the job's run history and log. pub async fn storage_run_sync_job( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = body.id.clone(); if storage::s3_sync::is_running(&id) { return HttpResponse::Conflict().json(serde_json::json!({ "error": "A pass for this job is already running" })); } // Fail fast on a dead job id — the spawn below can't report back. if !storage::s3_sync::load().jobs.iter().any(|j| j.id == id) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Sync job '{}' not found", id) })); } tokio::task::spawn_blocking(move || { if let Err(e) = storage::s3_sync::run_job(&id) { tracing::warn!("manual s3-sync run failed to start: {}", e); } }); HttpResponse::Ok().json(serde_json::json!({ "message": "Pass started — watch the job's log and run history" })) } /// GET /api/storage/s3-sync/log?id=… — tail of a job's rclone log pub async fn storage_sync_job_log( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = query.id.clone(); let result = web::block(move || storage::s3_sync::read_job_log(&id, 64 * 1024)).await; match result { Ok(log) => HttpResponse::Ok().json(serde_json::json!({ "log": log })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/s3-remotes/health — background-probe state per remote id pub async fn storage_s3_remote_health( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(storage::s3_health::health_snapshot()) } #[derive(Deserialize)] pub struct S3HealthToggleRequest { pub id: String, pub disabled: bool, } /// POST /api/storage/s3-remotes/health/toggle — opt a remote in/out of /// background probing (out for metered/egress-billed endpoints) pub async fn storage_s3_remote_health_toggle( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } storage::s3_health::set_probe_disabled(&body.id, body.disabled); HttpResponse::Ok().json(serde_json::json!({ "message": if body.disabled { format!("Background health checks disabled for {}", body.id) } else { format!("Background health checks enabled for {}", body.id) } })) } /// POST /api/storage/s3-remotes — create or update a saved credential set pub async fn storage_save_s3_remote( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let remote = storage::S3Remote { id: String::new(), // assigned from the name by save_s3_remote name: body.name.clone(), provider: if body.provider.is_empty() { "AWS".to_string() } else { body.provider.clone() }, endpoint: body.endpoint.clone(), region: body.region.clone(), access_key_id: body.access_key_id.clone(), secret_access_key: body.secret_access_key.clone(), origin: String::new(), // assigned by save_s3_remote }; match storage::save_s3_remote(remote) { // Return the secret-free view — the caller gets the assigned id // without the response carrying the key back out to the browser. Ok(saved) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Saved S3 credentials “{}”", saved.name), "id": saved.id, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// The remote id is carried as a query/body field rather than a path segment: /// ids are `:` and the name is operator-supplied, so a path /// segment would break on any name containing a slash. #[derive(Deserialize)] pub struct S3RemoteIdQuery { pub id: String, } /// POST /api/storage/s3-remotes/delete — forget a saved credential set pub async fn storage_delete_s3_remote( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match storage::delete_s3_remote(&body.id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": "Saved credentials removed" })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/storage/s3-remotes/buckets?id=… — buckets these credentials see /// /// Lets the operator pick a bucket instead of typing one: a wrong bucket name /// is otherwise only discovered when the s3fs daemon fails its startup check. pub async fn storage_s3_remote_buckets( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = query.id.clone(); // web::block — list_remote_buckets builds its own current-thread runtime, // which panics if constructed inside the actix worker's runtime. let result = web::block(move || storage::list_remote_buckets(&id)).await; match result { Ok(Ok(buckets)) => HttpResponse::Ok().json(serde_json::json!({ "buckets": buckets })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/providers — list installed storage providers pub async fn storage_list_providers( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(storage::list_providers()) } /// POST /api/storage/providers/{name}/install — install a storage provider pub async fn storage_install_provider( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let result = web::block(move || storage::install_provider(&name)).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/storage/providers/{name}/action — start/stop/restart a provider service /// Supports ?runtime=docker|lxc&target=containerName to manage inside containers pub async fn storage_provider_action( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); let action = body.get("action").and_then(|v| v.as_str()).unwrap_or("").to_string(); let result = web::block(move || storage::provider_action_targeted(&name, &action, &target)).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/providers/{name}/config — read a provider's config file pub async fn storage_provider_config( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); match storage::provider_config(&name) { Ok(content) => HttpResponse::Ok().json(serde_json::json!({ "content": content, "name": name })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "content": "", "error": e, "name": name })), } } /// POST /api/storage/providers/{name}/config — save a provider's config file pub async fn storage_provider_config_save( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let content = body.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string(); let result = web::block(move || storage::save_provider_config(&name, &content)).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct SystemLogsQuery { pub lines: Option, pub search: Option, pub unit: Option, /// journalctl boot selector: a boot id or relative index (0, -1, …). pub boot: Option, } /// GET /api/system/logs — read system journal logs pub async fn system_logs( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let q = query.into_inner(); let lines = q.lines.unwrap_or(200).min(5000); let boot = match q.boot.as_deref().filter(|b| !b.trim().is_empty()) { None => None, Some(b) => match crate::boot_history::validate_boot_selector(b) { Some(v) => Some(v), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid boot: expected a boot id or a number from -999 to 0" })), }, }; // journalctl can take seconds on a large journal — keep it off the // async worker. let logs = match web::block(move || storage::read_system_logs( lines, q.search.as_deref(), q.unit.as_deref(), boot.as_deref(), )).await { Ok(l) => l, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), }; HttpResponse::Ok().json(serde_json::json!({ "lines": logs, "count": logs.len(), })) } /// GET /api/system/boots — recorded boots with first/last log time and /// whether each ended with a logged shutdown, plus journal persistence state. pub async fn system_boots(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::boot_history::list_boots).await { Ok(report) => HttpResponse::Ok().json(report), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/system/journal/persistent — make journald keep logs on disk so /// the previous boot's log survives a crash. pub async fn system_journal_persistent(req: HttpRequest, state: web::Data) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(e) => return e }; tracing::info!("journal: {} enabled persistent journald storage", caller); match web::block(crate::boot_history::enable_persistent_journal).await { Ok(Ok(status)) => HttpResponse::Ok().json(serde_json::json!({ "status": status })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// GET /api/system/pstore — kernel crash dumps preserved across a reset. pub async fn system_pstore(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(crate::boot_history::list_pstore).await { Ok(files) => HttpResponse::Ok().json(serde_json::json!({ "files": files })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(Deserialize)] pub struct PstoreFileQuery { pub path: String } /// GET /api/system/pstore/file?path= — one pstore dump as text (bounded; /// only paths inside the pstore directories are served). pub async fn system_pstore_file(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let path = query.into_inner().path; match web::block(move || crate::boot_history::read_pstore_file(&path)).await { Ok(Ok((text, truncated))) => HttpResponse::Ok().json(serde_json::json!({ "text": text, "truncated": truncated })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/storage/mounts/{id}/sync — sync a global mount to all cluster nodes pub async fn storage_sync_mount( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); let config = storage::load_config(); let mount = match config.mounts.iter().find(|m| m.id == id) { Some(m) => m.clone(), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Mount not found" })), }; match sync_mount_to_cluster(&state, &mount).await { Ok(results) => HttpResponse::Ok().json(serde_json::json!({ "message": "Sync complete", "results": results })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/storage/mounts/{id}/sync-s3 — sync local changes back to S3 bucket pub async fn storage_sync_s3( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let id = path.into_inner(); // Run in blocking thread since S3 upload may take a while let result = web::block(move || { storage::sync_to_s3(&id) }).await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } // ─── Disk Partition Info ─── /// GET /api/storage/disk-info — list all block devices, partitions, filesystems & free space /// GET /api/storage/wolfdisk/status — live WolfDisk cluster/sync health for THIS /// node, read from the daemon's cluster_status.json. The WolfDisk tab fans this /// out across cluster members (via the node proxy) and compares index_version to /// flag out-of-sync nodes. klasSponsor 2026-06 sync healthcheck. pub async fn storage_wolfdisk_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match crate::storage::wolfdisk_cluster_status() { Some(status) => HttpResponse::Ok().json(status), None => HttpResponse::Ok().json(serde_json::json!({ "running": false, "error": "WolfDisk is not running on this node, or hasn't written a status file yet" })), } } pub async fn storage_disk_info(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // Run lsblk in JSON mode with useful columns let lsblk_out = std::process::Command::new("lsblk") .args([ "-J", "-o", "NAME,SIZE,FSTYPE,LABEL,MOUNTPOINTS,TYPE,HOTPLUG,ROTA,MODEL,SERIAL,UUID,PTTYPE,TRAN", "--bytes", ]) .output(); let block_devices: serde_json::Value = match lsblk_out { Ok(o) if o.status.success() => { let text = String::from_utf8_lossy(&o.stdout); serde_json::from_str(&text).unwrap_or_else(|_| serde_json::json!({ "blockdevices": [] })) } _ => serde_json::json!({ "blockdevices": [] }), }; // Run df to get free-space per mount point let df_out = std::process::Command::new("df") .args(["-B1", "--output=target,avail,size,pcent"]) .output(); let mut df_map: std::collections::HashMap = std::collections::HashMap::new(); if let Ok(o) = df_out { let text = String::from_utf8_lossy(&o.stdout); for line in text.lines().skip(1) { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() >= 4 { let mountpoint = parts[0].to_string(); let avail_bytes: u64 = parts[1].parse().unwrap_or(0); let total_bytes: u64 = parts[2].parse().unwrap_or(0); let use_pct = parts[3].trim_end_matches('%'); let use_pct: f64 = use_pct.parse().unwrap_or(0.0); let free_pct = (100.0 - use_pct).max(0.0); df_map.insert(mountpoint, serde_json::json!({ "avail_bytes": avail_bytes, "total_bytes": total_bytes, "use_pct": use_pct, "free_pct": free_pct, })); } } } // Walk lsblk tree and flatten into a list of partitions/disks with free-space data fn fmt_bytes(b: u64) -> String { const TB: u64 = 1_099_511_627_776; const GB: u64 = 1_073_741_824; const MB: u64 = 1_048_576; if b >= TB { format!("{:.1} TB", b as f64 / TB as f64) } else if b >= GB { format!("{:.1} GB", b as f64 / GB as f64) } else if b >= MB { format!("{:.1} MB", b as f64 / MB as f64) } else { format!("{} B", b) } } fn walk_devices( devices: &[serde_json::Value], df_map: &std::collections::HashMap, parent_disk: &str, parent_model: &str, out: &mut Vec, ) { for dev in devices { let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or(""); let dev_path = format!("/dev/{}", name); let size_bytes: u64 = dev.get("size") .and_then(|v| v.as_str()) .and_then(|s| s.parse().ok()) .or_else(|| dev.get("size").and_then(|v| v.as_u64())) .unwrap_or(0); let size_str = fmt_bytes(size_bytes); let fstype = dev.get("fstype").and_then(|v| v.as_str()).unwrap_or("").to_string(); let label = dev.get("label").and_then(|v| v.as_str()).unwrap_or("").to_string(); let kind = dev.get("type").and_then(|v| v.as_str()).unwrap_or("").to_string(); let model = dev.get("model").and_then(|v| v.as_str()).unwrap_or(parent_model).to_string(); let hotplug = dev.get("hotplug").and_then(|v| v.as_bool()).unwrap_or(false); let rotational = dev.get("rota").and_then(|v| v.as_bool()).unwrap_or(true); let serial = dev.get("serial").and_then(|v| v.as_str()).unwrap_or("").to_string(); let uuid = dev.get("uuid").and_then(|v| v.as_str()).unwrap_or("").to_string(); let pttype = dev.get("pttype").and_then(|v| v.as_str()).unwrap_or("").to_string(); let tran = dev.get("tran").and_then(|v| v.as_str()).unwrap_or("").to_string(); // Collect mountpoints let mounts: Vec = dev.get("mountpoints") .and_then(|v| v.as_array()) .map(|arr| arr.iter() .filter_map(|m| m.as_str()) .filter(|s| !s.is_empty()) .map(|s| s.to_string()) .collect()) .unwrap_or_default(); // Get df data for the first mount point let df = mounts.first() .and_then(|mp| df_map.get(mp.as_str())) .cloned() .unwrap_or(serde_json::json!(null)); let disk_name = if kind == "disk" { name } else { parent_disk }; let disk_model = if kind == "disk" { &model } else { parent_model }; out.push(serde_json::json!({ "device": dev_path, "disk": format!("/dev/{}", disk_name), "model": disk_model, "type": kind, "size": size_str, "size_bytes": size_bytes, "fstype": if fstype.is_empty() { serde_json::json!(null) } else { serde_json::json!(fstype) }, "label": if label.is_empty() { serde_json::json!(null) } else { serde_json::json!(label) }, "mountpoints": mounts, "hotplug": hotplug, "rotational": rotational, "serial": if serial.is_empty() { serde_json::json!(null) } else { serde_json::json!(serial) }, "uuid": if uuid.is_empty() { serde_json::json!(null) } else { serde_json::json!(uuid) }, "pttype": if pttype.is_empty() { serde_json::json!(null) } else { serde_json::json!(pttype) }, "tran": if tran.is_empty() { serde_json::json!(null) } else { serde_json::json!(tran) }, "df": df, })); // Recurse into children (partitions) if let Some(children) = dev.get("children").and_then(|v| v.as_array()) { walk_devices(children, df_map, disk_name, disk_model, out); } } } let mut entries: Vec = Vec::new(); if let Some(devs) = block_devices.get("blockdevices").and_then(|v| v.as_array()) { walk_devices(devs, &df_map, "", "", &mut entries); } // Collect SMART health for physical disks (best-effort, smartctl may not be installed) let has_smartctl = std::process::Command::new("which") .arg("smartctl") .output() .map(|o| o.status.success()) .unwrap_or(false); if has_smartctl { let mut smart_map: std::collections::HashMap = std::collections::HashMap::new(); for entry in &entries { if entry.get("type").and_then(|v| v.as_str()) == Some("disk") && let Some(dev) = entry.get("device").and_then(|v| v.as_str()) { if dev.starts_with("/dev/loop") { continue; } // Shared evaluator — same parse + failing verdict the Issues // watcher uses, so the Storage badge and the Issues alert can // never disagree. respect_standby=false: an interactive // Storage read may wake a spun-down disk (the watcher won't). if let Some(smart) = crate::array::disk_smart_health(dev, false) { let reasons = smart.failing_reasons(); let mut sj = serde_json::to_value(&smart).unwrap_or_default(); if let Some(obj) = sj.as_object_mut() { obj.insert("failing".to_string(), serde_json::json!(!reasons.is_empty())); obj.insert("reasons".to_string(), serde_json::json!(reasons)); } smart_map.insert(dev.to_string(), sj); } } } // Attach SMART data to disk entries for entry in &mut entries { if let Some(dev) = entry.get("device").and_then(|v| v.as_str()).map(|s| s.to_string()) && let Some(smart) = smart_map.get(&dev) { entry.as_object_mut().map(|m| m.insert("smart".to_string(), smart.clone())); } } } // Network / cluster filesystems (GlusterFS, NFS, CIFS, SSHFS, s3fs, CephFS, // WolfDisk) never appear in lsblk — they aren't block devices — so the node // Storage view silently omitted them (Paul 2026-07-03: a gluster mount was // invisible). Parse /proc/mounts and join usage from the same df snapshot // the disk entries use. let mut network_mounts: Vec = Vec::new(); if let Ok(mounts) = std::fs::read_to_string("/proc/mounts") { for line in mounts.lines() { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() < 3 { continue; } let (source, target, fstype) = (parts[0], parts[1], parts[2]); let is_net = matches!(fstype, "fuse.glusterfs" | "nfs" | "nfs4" | "cifs" | "smb3" | "fuse.sshfs" | "fuse.s3fs" | "fuse.rclone" | "ceph") // WolfDisk mounts with FSName("wolfdisk") and no fuse subtype // (wolfdisk/src/main.rs:2481), so it shows as fstype "fuse" // with the fsname as the source field. || (fstype == "fuse" && source == "wolfdisk"); if !is_net { continue; } // /proc/mounts octal-escapes spaces in paths as \040. let target_clean = target.replace("\\040", " "); let df = df_map.get(target_clean.as_str()).cloned() .unwrap_or(serde_json::Value::Null); network_mounts.push(serde_json::json!({ "source": source, "mountpoint": target_clean, "fstype": fstype, "df": df, })); } } HttpResponse::Ok().json(serde_json::json!({ "devices": entries, "network_mounts": network_mounts, })) } // ─── Disk Partitioning & Formatting ─── #[derive(Deserialize)] pub struct CreatePartitionTableRequest { pub disk: String, pub table_type: String, // "gpt" or "msdos" } /// POST /api/storage/disk/partition-table — create a partition table pub async fn disk_create_partition_table( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let disk = body.disk.clone(); let table_type = body.table_type.clone(); match web::block(move || storage::create_partition_table(&disk, &table_type)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct CreatePartitionRequest { pub disk: String, #[serde(default)] pub size_mb: Option, // None = use all remaining space #[serde(default)] pub fs_type_hint: Option, } /// POST /api/storage/disk/partition — create a partition pub async fn disk_create_partition( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let disk = body.disk.clone(); let size_mb = body.size_mb; let hint = body.fs_type_hint.clone(); match web::block(move || storage::create_partition(&disk, size_mb, hint.as_deref())).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct DeletePartitionRequest { pub device: String, } /// POST /api/storage/disk/partition/delete — delete a partition pub async fn disk_delete_partition( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let device = body.device.clone(); match web::block(move || storage::delete_partition(&device)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct FormatPartitionRequest { pub device: String, pub fstype: String, #[serde(default)] pub label: Option, } /// POST /api/storage/disk/format — format a partition pub async fn disk_format_partition( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let device = body.device.clone(); let fstype = body.fstype.clone(); let label = body.label.clone(); match web::block(move || storage::format_partition(&device, &fstype, label.as_deref())).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct DedicateDiskRequest { pub device: String, pub fstype: String, } /// POST /api/storage/wolfdisk/dedicate-disk — wipe a whole disk, migrate /// WolfDisk's data onto it, mount it at WolfDisk's data_dir + fstab, restart the /// daemon. DESTRUCTIVE: the frontend confirms the wipe before calling. klasSponsor. pub async fn disk_dedicate_wolfdisk( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let device = body.device.clone(); let fstype = body.fstype.clone(); match web::block(move || storage::wolfdisk_dedicate_disk(&device, &fstype)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } #[derive(Deserialize)] pub struct ResizePartitionRequest { pub device: String, } /// POST /api/storage/disk/resize — grow a partition and its filesystem pub async fn disk_resize_partition( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let device = body.device.clone(); match web::block(move || storage::resize_partition(&device)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({"ok": true, "message": msg})), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": e})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("{}", e)})), } } /// GET /api/storage/disk/filesystems — list supported filesystem types pub async fn disk_supported_filesystems( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(storage::SUPPORTED_FILESYSTEMS) } // ─── ZFS Storage ─── /// GET /api/storage/zfs/status — check if ZFS is available and return overview pub async fn zfs_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let available = std::process::Command::new("which").arg("zfs").output() .map(|o| o.status.success()).unwrap_or(false); if !available { return HttpResponse::Ok().json(serde_json::json!({ "available": false, "pools": [] })); } // Get pool summary let pools = zfs_get_pools(); HttpResponse::Ok().json(serde_json::json!({ "available": true, "pools": pools, // e.g. "zfs-2.4.2-1~bpo13+1" — surfaced so admins can see what their // installed OpenZFS supports (and why AnyRaid isn't offered yet). "version": zfs_version_string(), })) } /// GET /api/storage/zfs/pools — list all ZFS pools with usage stats pub async fn zfs_pools(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(zfs_get_pools()) } /// GET /api/storage/zfs/datasets?pool=POOL — list datasets for a pool pub async fn zfs_datasets(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = query.get("pool").cloned().unwrap_or_default(); if pool.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'pool' parameter" })); } // Validate pool name (alphanumeric, dash, underscore, dot only) if !pool.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } let output = std::process::Command::new("zfs") .args(["list", "-H", "-r", "-o", "name,used,avail,refer,mountpoint,compression,compressratio", &pool]) .output(); match output { Ok(out) if out.status.success() => { let text = String::from_utf8_lossy(&out.stdout); let datasets: Vec = text.lines() .filter(|l| !l.is_empty()) .map(|line| { let parts: Vec<&str> = line.split('\t').collect(); serde_json::json!({ "name": parts.first().unwrap_or(&""), "used": parts.get(1).unwrap_or(&""), "available": parts.get(2).unwrap_or(&""), "refer": parts.get(3).unwrap_or(&""), "mountpoint": parts.get(4).unwrap_or(&""), "compression": parts.get(5).unwrap_or(&""), "compressratio": parts.get(6).unwrap_or(&""), }) }) .collect(); HttpResponse::Ok().json(datasets) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/zfs/snapshots?dataset=DATASET — list snapshots pub async fn zfs_snapshots(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let dataset = query.get("dataset").cloned().unwrap_or_default(); let mut args = vec!["list", "-t", "snapshot", "-H", "-o", "name,creation,used,refer"]; if !dataset.is_empty() { if !dataset.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/' || c == '@') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid dataset name" })); } args.push("-r"); args.push(&dataset); } let output = std::process::Command::new("zfs").args(&args).output(); match output { Ok(out) if out.status.success() => { let text = String::from_utf8_lossy(&out.stdout); let snapshots: Vec = text.lines() .filter(|l| !l.is_empty()) .map(|line| { let parts: Vec<&str> = line.split('\t').collect(); serde_json::json!({ "name": parts.first().unwrap_or(&""), "creation": parts.get(1).unwrap_or(&""), "used": parts.get(2).unwrap_or(&""), "refer": parts.get(3).unwrap_or(&""), }) }) .collect(); HttpResponse::Ok().json(snapshots) } Ok(out) => { let _err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::Ok().json(Vec::::new()) // empty list if no snapshots } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/storage/zfs/snapshot — create a snapshot pub async fn zfs_create_snapshot(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let dataset = body.get("dataset").and_then(|v| v.as_str()).unwrap_or(""); let snap_name = body.get("name").and_then(|v| v.as_str()).unwrap_or(""); if dataset.is_empty() || snap_name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'dataset' or 'name'" })); } // Validate names let valid_chars = |s: &str| s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/'); if !valid_chars(dataset) || !valid_chars(snap_name) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid characters in dataset or snapshot name" })); } let snapshot_full = format!("{}@{}", dataset, snap_name); let output = std::process::Command::new("zfs") .args(["snapshot", &snapshot_full]) .output(); match output { Ok(out) if out.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "message": format!("Snapshot '{}' created", snapshot_full) })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// DELETE /api/storage/zfs/snapshot — delete a snapshot pub async fn zfs_delete_snapshot(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let snapshot = body.get("snapshot").and_then(|v| v.as_str()).unwrap_or(""); if snapshot.is_empty() || !snapshot.contains('@') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid snapshot name (must contain @)" })); } if !snapshot.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/' || c == '@') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid characters in snapshot name" })); } let output = std::process::Command::new("zfs") .args(["destroy", snapshot]) .output(); match output { Ok(out) if out.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "message": format!("Snapshot '{}' deleted", snapshot) })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// Helper: parse zpool list output into JSON fn zfs_get_pools() -> Vec { let output = std::process::Command::new("zpool") .args(["list", "-H", "-o", "name,size,alloc,free,health,fragmentation,capacity,dedup,altroot"]) .output(); match output { Ok(out) if out.status.success() => { let mut pools: Vec = String::from_utf8_lossy(&out.stdout).lines() .filter(|l| !l.is_empty()) .map(|line| { let parts: Vec<&str> = line.split('\t').collect(); serde_json::json!({ "name": parts.first().unwrap_or(&""), "size": parts.get(1).unwrap_or(&""), "alloc": parts.get(2).unwrap_or(&""), "free": parts.get(3).unwrap_or(&""), "health": parts.get(4).unwrap_or(&""), "fragmentation": parts.get(5).unwrap_or(&""), "capacity": parts.get(6).unwrap_or(&""), "dedup": parts.get(7).unwrap_or(&"1.00x"), "altroot": parts.get(8).unwrap_or(&"-"), }) }) .collect(); // Enrich each pool with scan/scrub status from `zpool status` for pool in &mut pools { let pool_name = pool["name"].as_str().unwrap_or("").to_string(); if let Ok(status_out) = std::process::Command::new("zpool") .args(["status", &pool_name]) .output() && status_out.status.success() { let status_text = String::from_utf8_lossy(&status_out.stdout).to_string(); // Extract scan line let scan_line = status_text.lines() .find(|l| l.trim_start().starts_with("scan:")) .map(|l| l.trim_start().trim_start_matches("scan:").trim().to_string()) .unwrap_or_else(|| "none requested".to_string()); // Extract errors line let errors_line = status_text.lines() .find(|l| l.trim_start().starts_with("errors:")) .map(|l| l.trim_start().trim_start_matches("errors:").trim().to_string()) .unwrap_or_else(|| "unknown".to_string()); pool["scan"] = serde_json::json!(scan_line); pool["errors"] = serde_json::json!(errors_line); } } pools } _ => vec![], } } /// POST /api/storage/zfs/pool/scrub — start or stop a scrub pub async fn zfs_pool_scrub( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = body.get("pool").and_then(|v| v.as_str()).unwrap_or("").trim(); let stop = body.get("stop").and_then(|v| v.as_bool()).unwrap_or(false); if pool.is_empty() || pool.contains("..") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } let mut args = vec!["scrub"]; if stop { args.push("-s"); } args.push(pool); let output = std::process::Command::new("zpool").args(&args).output(); match output { Ok(out) if out.status.success() => { let msg = if stop { format!("Scrub stopped on pool '{}'", pool) } else { format!("Scrub started on pool '{}'", pool) }; HttpResponse::Ok().json(serde_json::json!({ "message": msg })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/zfs/pool/status?pool=POOL — detailed pool status (vdevs, errors, scan) pub async fn zfs_pool_status( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = query.get("pool").cloned().unwrap_or_default(); let pool = pool.trim().to_string(); if pool.is_empty() || pool.contains("..") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } let output = std::process::Command::new("zpool").args(["status", "-v", &pool]).output(); match output { Ok(out) if out.status.success() => { let text = String::from_utf8_lossy(&out.stdout).to_string(); HttpResponse::Ok().json(serde_json::json!({ "pool": pool, "status_text": text, })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/storage/zfs/pool/iostat?pool=POOL — pool IO statistics pub async fn zfs_pool_iostat( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = query.get("pool").cloned().unwrap_or_default(); let pool = pool.trim().to_string(); if pool.is_empty() || pool.contains("..") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } let output = std::process::Command::new("zpool").args(["iostat", "-v", &pool]).output(); match output { Ok(out) if out.status.success() => { let text = String::from_utf8_lossy(&out.stdout).to_string(); HttpResponse::Ok().json(serde_json::json!({ "pool": pool, "iostat_text": text, })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// First line of `zfs version` (e.g. "zfs-2.4.2-1~bpo13+1"), or None if it /// can't be read. Shown in the UI so admins know what their installed OpenZFS /// can and can't do (klasSponsor 2026-07-22 asked for AnyRaid management — /// AnyRaid is not in any RELEASED OpenZFS as of 2026-07, so the UI shows the /// version plus an honest "pending upstream" note instead of unusable options). fn zfs_version_string() -> Option { let out = std::process::Command::new("zfs").arg("version").output().ok()?; if !out.status.success() { return None; } String::from_utf8_lossy(&out.stdout) .lines() .next() .map(|l| l.trim().to_string()) } /// Valid ZFS pool name: begins with a letter; letters/digits/-_.: after; not a /// reserved vdev keyword (zpoolconcepts(7): mirror/raidz/draid/spare/log). fn valid_zpool_name(name: &str) -> bool { let mut chars = name.chars(); let first_ok = chars.next().map(|c| c.is_ascii_alphabetic()).unwrap_or(false); let rest_ok = name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')); let reserved = ["mirror", "raidz", "draid", "spare", "log"]; let not_reserved = !reserved.iter().any(|r| name == *r || name.starts_with(&format!("{}0", r)) || name.starts_with(&format!("{}1", r)) || name.starts_with(&format!("{}2", r)) || name.starts_with(&format!("{}3", r))); first_ok && rest_ok && not_reserved } /// GET /api/storage/zfs/importable — pools visible to `zpool import` (exported /// or foreign, e.g. a disk shelf pulled from a TrueNAS box — TrueNAS pools are /// plain OpenZFS, so migrating to WolfStack is a straight import). pub async fn zfs_importable(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } // `zpool import` scans every device; seconds, not millis — off the runtime. let output = web::block(|| std::process::Command::new("zpool").arg("import").output()).await; let output = match output { Ok(Ok(o)) => o, _ => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "zpool import failed to run" })), }; // Exit status is non-zero when there is nothing to import — that's an // empty list, not an error. let text = format!( "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) ); let mut pools: Vec = Vec::new(); let mut current: Option<(String, String, String)> = None; // name, id, state for line in text.lines() { let t = line.trim(); if let Some(rest) = t.strip_prefix("pool:") { if let Some((n, i, s)) = current.take() { pools.push(serde_json::json!({ "name": n, "id": i, "state": s })); } current = Some((rest.trim().to_string(), String::new(), String::new())); } else if let Some(rest) = t.strip_prefix("id:") && let Some(c) = current.as_mut() { c.1 = rest.trim().to_string(); } else if let Some(rest) = t.strip_prefix("state:") && let Some(c) = current.as_mut() { c.2 = rest.trim().to_string(); } } if let Some((n, i, s)) = current.take() { pools.push(serde_json::json!({ "name": n, "id": i, "state": s })); } HttpResponse::Ok().json(serde_json::json!({ "pools": pools })) } /// POST /api/storage/zfs/pool/import — {pool, force?} import by name or id. /// `force` maps to `zpool import -f` (pool last used on another system — the /// normal case for a TrueNAS migration, where the pool was never exported). pub async fn zfs_pool_import( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = body.get("pool").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let force = body.get("force").and_then(|v| v.as_bool()).unwrap_or(false); // Accept a pool name or a numeric pool id. let is_id = !pool.is_empty() && pool.chars().all(|c| c.is_ascii_digit()); if pool.is_empty() || (!is_id && !valid_zpool_name(&pool)) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } let output = web::block(move || { let mut args: Vec<&str> = vec!["import"]; if force { args.push("-f"); } args.push(&pool); std::process::Command::new("zpool").args(&args).output() .map(|o| (o, pool.clone())) }) .await; match output { Ok(Ok((out, pool))) if out.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "message": format!("Pool '{}' imported", pool) })) } Ok(Ok((out, _))) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } _ => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "zpool import failed to run" })), } } /// POST /api/storage/zfs/pool/create — {name, layout, disks[], mountpoint?, force?}. /// /// Layouts are the RELEASED OpenZFS vdev types only (stripe/mirror/raidz1-3). /// AnyRaid/anymirror (mixed-size vdevs) is deliberately NOT offered: it is not /// in any released OpenZFS (still in review upstream as of 2026-07) and its /// final CLI syntax is not frozen — offering it would ship guessed commands. /// The UI explains this; support lands here the release after OpenZFS ships it. /// /// DESTRUCTIVE: creating a pool takes ownership of the member disks. Every /// disk must pass the same paranoid in-use gate as dedicate-disk /// (mounted/LVM/mdraid/LUKS/swap/ZFS/bcache/Ceph anywhere on the device) — /// `force` does NOT bypass that gate, it only maps to `zpool create -f` /// (which clears foreign non-active labels). A disk that is part of the /// running system can never be pulled into a pool through this endpoint. pub async fn zfs_pool_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let layout = body.get("layout").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let force = body.get("force").and_then(|v| v.as_bool()).unwrap_or(false); let mountpoint = body.get("mountpoint").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let disks: Vec = body.get("disks").and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|d| d.as_str()).map(|s| s.trim().to_string()).collect()) .unwrap_or_default(); if !valid_zpool_name(&name) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name (must start with a letter; letters, digits, - _ . : only)" })); } // (vdev keyword, minimum devices) per zpoolconcepts(7). let (vdev_kw, min_disks): (Option<&str>, usize) = match layout.as_str() { "stripe" => (None, 1), "mirror" => (Some("mirror"), 2), "raidz1" => (Some("raidz1"), 2), "raidz2" => (Some("raidz2"), 3), "raidz3" => (Some("raidz3"), 4), _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid layout (stripe, mirror, raidz1, raidz2, raidz3)" })), }; if disks.len() < min_disks { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Layout '{}' needs at least {} disks", layout, min_disks) })); } if !mountpoint.is_empty() && (!mountpoint.starts_with('/') || mountpoint.contains("..")) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Mountpoint must be an absolute path" })); } for d in &disks { if !d.starts_with("/dev/") || d.contains("..") || d.chars().any(|c| c.is_whitespace()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid device path: {}", d) })); } if !std::path::Path::new(d).exists() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Device not found: {}", d) })); } } let mut seen = std::collections::HashSet::new(); if !disks.iter().all(|d| seen.insert(d.clone())) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Duplicate device in disk list" })); } let result = web::block(move || -> Result { // Safety gates — never overridable from the API (matches dedicate-disk). for d in &disks { if storage::is_protected_device(d)? { return Err(format!("{} holds a protected system mountpoint — refusing", d)); } if storage::device_or_children_in_use(d)? { return Err(format!( "{} is in use (mounted, or holds LVM/mdraid/LUKS/swap/ZFS/bcache/Ceph data) — \ clear it first if it really is expendable", d )); } } let mut args: Vec = vec!["create".into()]; if force { args.push("-f".into()); } if !mountpoint.is_empty() { args.push("-m".into()); args.push(mountpoint.clone()); } args.push(name.clone()); if let Some(kw) = vdev_kw { args.push(kw.into()); } args.extend(disks.iter().cloned()); let out = std::process::Command::new("zpool").args(&args).output() .map_err(|e| format!("zpool: {}", e))?; if out.status.success() { Ok(format!("Pool '{}' created ({} on {} disks)", name, layout, disks.len())) } else { Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) } }) .await; match result { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// DELETE /api/storage/zfs/pool — {pool, confirm} destroy a pool. `confirm` /// must EXACTLY equal the pool name (the UI makes the admin type it) — this is /// an irreversible, whole-pool data loss operation. pub async fn zfs_pool_destroy( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let pool = body.get("pool").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let confirm = body.get("confirm").and_then(|v| v.as_str()).unwrap_or("").trim(); if !valid_zpool_name(&pool) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid pool name" })); } if confirm != pool { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Confirmation text does not match the pool name" })); } let output = web::block(move || { std::process::Command::new("zpool").args(["destroy", &pool]).output() .map(|o| (o, pool.clone())) }) .await; match output { Ok(Ok((out, pool))) if out.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "message": format!("Pool '{}' destroyed", pool) })) } Ok(Ok((out, _))) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } _ => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "zpool destroy failed to run" })), } } /// POST /api/storage/zfs/dataset — {name} create a dataset (name must be /// pool/path, validated to the zfs charset). pub async fn zfs_dataset_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let valid = !name.is_empty() && name.contains('/') && !name.contains("..") && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':')) && !name.starts_with('/') && !name.ends_with('/'); if !valid { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid dataset name (pool/path)" })); } let output = std::process::Command::new("zfs").args(["create", "-p", &name]).output(); match output { Ok(out) if out.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "message": format!("Dataset '{}' created", name) })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": err.trim() })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── File Manager ─── /// Validate and normalize a file path — prevent traversal attacks fn sanitize_file_path(path: &str) -> Result { let p = std::path::Path::new(path); // Must be absolute if !p.is_absolute() { return Err("Path must be absolute".into()); } // Canonicalize to resolve .. and symlinks match p.canonicalize() { Ok(canonical) => Ok(canonical), Err(_) => { // For paths that don't exist yet (e.g., mkdir), check the parent if let Some(parent) = p.parent() { if let Ok(canonical_parent) = parent.canonicalize() { let file_name = p.file_name().ok_or("Invalid path")?; Ok(canonical_parent.join(file_name)) } else { Err("Parent directory does not exist".into()) } } else { Err("Invalid path".into()) } } } } /// Check if a path is sensitive and should not be accessible via the file manager fn is_sensitive_path(path: &std::path::Path) -> bool { let s = path.to_string_lossy(); s == "/etc/wolfstack" || s.starts_with("/etc/wolfstack/") || s == "/etc/shadow" || s == "/etc/gshadow" || s == "/proc" || s.starts_with("/proc/") || s == "/sys" || s.starts_with("/sys/") || s == "/root/.ssh" || s.starts_with("/root/.ssh/") } /// GET /api/files/browse?path=/some/path — list directory contents pub async fn files_browse( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = query.get("path").cloned().unwrap_or_else(|| "/".into()); let canonical = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } if !canonical.is_dir() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a directory" })); } let mut entries = Vec::new(); match std::fs::read_dir(&canonical) { Ok(dir) => { for entry in dir.flatten() { let name = entry.file_name().to_string_lossy().to_string(); let meta = entry.metadata().ok(); let is_dir = meta.as_ref().map(|m| m.is_dir()).unwrap_or(false); let size = meta.as_ref().map(|m| m.len()).unwrap_or(0); let modified = meta.as_ref() .and_then(|m| m.modified().ok()) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| d.as_secs()) .unwrap_or(0); // Unix permissions #[cfg(unix)] let permissions = { use std::os::unix::fs::PermissionsExt; meta.as_ref() .map(|m| format!("{:o}", m.permissions().mode() & 0o7777)) .unwrap_or_default() }; #[cfg(not(unix))] let permissions = String::new(); let entry_path = canonical.join(&name); entries.push(serde_json::json!({ "name": name, "path": entry_path.to_string_lossy(), "is_dir": is_dir, "size": if is_dir { 0 } else { size }, "modified": modified, "permissions": permissions, })); } } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Cannot read directory: {}", e) })); } } // Sort: directories first, then alphabetically entries.sort_by(|a, b| { let a_dir = a["is_dir"].as_bool().unwrap_or(false); let b_dir = b["is_dir"].as_bool().unwrap_or(false); match (a_dir, b_dir) { (true, false) => std::cmp::Ordering::Less, (false, true) => std::cmp::Ordering::Greater, _ => a["name"].as_str().unwrap_or("") .to_lowercase() .cmp(&b["name"].as_str().unwrap_or("").to_lowercase()), } }); HttpResponse::Ok().json(serde_json::json!({ "path": canonical.to_string_lossy(), "entries": entries, })) } /// POST /api/files/mkdir — create directory pub async fn files_mkdir( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })); } let canonical = match sanitize_file_path(path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } match std::fs::create_dir_all(&canonical) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Directory created: {}", canonical.display()) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to create directory: {}", e) })), } } /// POST /api/files/delete — delete file or directory pub async fn files_delete( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })); } let canonical = match sanitize_file_path(path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } // Prevent deleting critical system paths let critical = ["/", "/etc", "/usr", "/bin", "/sbin", "/lib", "/lib64", "/boot", "/proc", "/sys", "/dev", "/var", "/root"]; if critical.contains(&canonical.to_string_lossy().as_ref()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot delete system directory" })); } let result = if canonical.is_dir() { std::fs::remove_dir_all(&canonical) } else { std::fs::remove_file(&canonical) }; match result { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Deleted: {}", canonical.display()) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to delete: {}", e) })), } } /// POST /api/files/rename — rename / move a file or directory pub async fn files_rename( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let from = body.get("from").and_then(|v| v.as_str()).unwrap_or(""); let to = body.get("to").and_then(|v| v.as_str()).unwrap_or(""); if from.is_empty() || to.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'from' or 'to'" })); } let from_path = match sanitize_file_path(from) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let to_path = match sanitize_file_path(to) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&from_path) || is_sensitive_path(&to_path) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } match std::fs::rename(&from_path, &to_path) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Renamed to {}", to_path.display()) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to rename: {}", e) })), } } /// POST /api/files/upload?path=/some/dir — upload file(s) via multipart pub async fn files_upload( req: HttpRequest, state: web::Data, query: web::Query>, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let dir = query.get("path").cloned().unwrap_or_else(|| "/tmp".into()); let canonical_dir = match sanitize_file_path(&dir) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical_dir) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access denied: protected path" })); } if !canonical_dir.is_dir() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Target is not a directory" })); } use futures::StreamExt; let mut uploaded = Vec::new(); while let Some(Ok(mut field)) = payload.next().await { let filename = field.content_disposition() .and_then(|cd| cd.get_filename().map(|s| s.to_string())) .unwrap_or_else(|| "upload".to_string()); // Sanitize filename — extract only the terminal component (immune to traversal) let safe_name = std::path::Path::new(&filename) .file_name() .and_then(|n| n.to_str()) .unwrap_or("upload") .to_string(); if safe_name.is_empty() || safe_name == "." { continue; } let file_path = canonical_dir.join(&safe_name); // tokio::fs, not std::fs — the sync writes ran on the async // worker, blocking it for the duration of every chunk flush // (sync-in-async sweep, phase 1a). let mut file = match tokio::fs::File::create(&file_path).await { Ok(f) => f, Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Cannot create file {}: {}", safe_name, e) })); } }; use tokio::io::AsyncWriteExt; while let Some(Ok(chunk)) = field.next().await { if file.write_all(&chunk).await.is_err() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write file {}", safe_name) })); } } uploaded.push(safe_name); } HttpResponse::Ok().json(serde_json::json!({ "message": format!("Uploaded {} file(s)", uploaded.len()), "files": uploaded, })) } /// `Content-Disposition: attachment` naming the saved file. Mirrors /// actix-files' own default (actix-files named.rs: `Filename`, plus a UTF-8 /// `FilenameExt` when the name is not ASCII) so non-ASCII names survive, and /// the typed header escapes quotes/backslashes that a hand-built /// `filename="…"` string would not. fn attachment_disposition(filename: String) -> actix_web::http::header::ContentDisposition { use actix_web::http::header::{Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue}; let ext = (!filename.is_ascii()).then(|| DispositionParam::FilenameExt(ExtendedValue { charset: Charset::Ext(String::from("UTF-8")), language_tag: None, value: filename.clone().into_bytes(), })); let mut parameters = vec![DispositionParam::Filename(filename)]; parameters.extend(ext); ContentDisposition { disposition: DispositionType::Attachment, parameters } } /// File name a download is saved under: the last component of `path`. fn download_filename(path: &std::path::Path) -> String { path.file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_else(|| "download".into()) } /// GET /api/files/download?path=/some/file — download a file pub async fn files_download( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = query.get("path").cloned().unwrap_or_default(); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })); } let canonical = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } if !canonical.is_file() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Not a file" })); } let filename = download_filename(&canonical); // Stream via NamedFile (chunked reads on the blocking pool) instead // of std::fs::read: the old path buffered the WHOLE file in RAM and // blocked the async worker for the entire read — a multi-GB download // pinned a worker and ballooned RSS (sync-in-async sweep, phase 1a). // The open+stat itself also goes through web::block: open_async is // NOT async without the io-uring feature, and a stat can stall for // hundreds of ms on NFS/SSHFS-backed paths. let canonical_c = canonical.clone(); let opened = match web::block(move || actix_files::NamedFile::open(&canonical_c)).await { Ok(r) => r, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })), }; match opened { Ok(nf) => nf .set_content_disposition(attachment_disposition(filename)) .into_response(&req), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Cannot read file: {}", e) })), } } /// GET /api/files/search?path=/start&query=pattern — recursive search using find pub async fn files_search( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let search_path = query.get("path").cloned().unwrap_or_else(|| "/".into()); let search_query = query.get("query").cloned().unwrap_or_default(); if search_query.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'query'" })); } let canonical = match sanitize_file_path(&search_path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; // Use find with -iname for case-insensitive matching, limit results let output = std::process::Command::new("find") .args([canonical.to_str().unwrap_or("/"), "-maxdepth", "8", "-iname", &format!("*{}*", search_query), "-printf", "%y\t%s\t%T@\t%m\t%p\n"]) .output(); match output { Ok(out) if out.status.success() => { let mut entries: Vec = String::from_utf8_lossy(&out.stdout) .lines() .filter(|l| !l.is_empty()) .take(100) // cap results .map(|line| { let parts: Vec<&str> = line.splitn(5, '\t').collect(); let file_type = parts.first().unwrap_or(&"f"); let size: u64 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); let modified: f64 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0.0); let permissions = parts.get(3).unwrap_or(&"").to_string(); let full_path = parts.get(4).unwrap_or(&"").to_string(); let name = std::path::Path::new(&full_path) .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_else(|| full_path.clone()); let is_dir = *file_type == "d"; serde_json::json!({ "name": name, "path": full_path, "is_dir": is_dir, "size": if is_dir { 0 } else { size }, "modified": modified as u64, "permissions": permissions, }) }) .collect(); entries.sort_by(|a, b| { let ad = a["is_dir"].as_bool().unwrap_or(false); let bd = b["is_dir"].as_bool().unwrap_or(false); match (ad, bd) { (true, false) => std::cmp::Ordering::Less, (false, true) => std::cmp::Ordering::Greater, _ => a["name"].as_str().unwrap_or("").to_lowercase() .cmp(&b["name"].as_str().unwrap_or("").to_lowercase()), } }); HttpResponse::Ok().json(serde_json::json!({ "path": search_path, "query": search_query, "entries": entries, })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::Ok().json(serde_json::json!({ "path": search_path, "query": search_query, "entries": [], "warning": err.trim(), })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/chmod — change permissions on a file or files pub async fn files_chmod( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let mode = body.get("mode").and_then(|v| v.as_str()).unwrap_or(""); let paths: Vec = body.get("paths") .and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()) .unwrap_or_default(); if mode.is_empty() || paths.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'mode' or 'paths'" })); } // Validate mode (must be octal like 755 or symbolic like u+x) if mode.len() > 10 || mode.contains("..") { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid mode" })); } let mut results = Vec::new(); for path in &paths { let canonical = match sanitize_file_path(path) { Ok(p) => p, Err(e) => { results.push(serde_json::json!({"path": path, "error": e})); continue; } }; let output = std::process::Command::new("chmod") .args([mode, canonical.to_str().unwrap_or("")]) .output(); match output { Ok(out) if out.status.success() => { results.push(serde_json::json!({"path": path, "ok": true})); } Ok(out) => { results.push(serde_json::json!({"path": path, "error": String::from_utf8_lossy(&out.stderr).trim().to_string()})); } Err(e) => { results.push(serde_json::json!({"path": path, "error": format!("{}", e)})); } } } HttpResponse::Ok().json(serde_json::json!({ "results": results })) } /// GET /api/files/read?path=/etc/hosts — read file contents as text pub async fn files_read( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = match query.get("path") { Some(p) => p.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let canonical = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access denied: protected path" })); } if canonical.is_dir() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot edit a directory" })); } let metadata = match std::fs::metadata(&canonical) { Ok(m) => m, Err(e) => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("File not found: {}", e) })), }; if metadata.len() > 2 * 1024 * 1024 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "File too large to edit (max 2MB)" })); } match std::fs::read_to_string(&canonical) { Ok(content) => HttpResponse::Ok().json(serde_json::json!({ "path": path, "content": content, "size": metadata.len(), })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Cannot read file (binary?): {}", e) })), } } /// POST /api/files/write — write text content to a file pub async fn files_write( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let path = match body.get("path").and_then(|v| v.as_str()) { Some(p) => p.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let content = match body.get("content").and_then(|v| v.as_str()) { Some(c) => c, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'content'" })), }; let canonical = match sanitize_file_path(&path) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; if is_sensitive_path(&canonical) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Access to this path is restricted" })); } if canonical.is_dir() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot write to a directory" })); } match std::fs::write(&canonical, content) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "File saved", "path": path })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Write failed: {}", e) })), } } /// GET /api/files/docker/browse?container=ID&path=/ — browse files inside a Docker container pub async fn files_docker_browse( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let path = query.get("path").cloned().unwrap_or_else(|| "/".into()); if container.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })); } // Use docker exec to list directory contents with stat-like output let output = std::process::Command::new("docker") .args(["exec", &container, "find", &path, "-maxdepth", "1", "-mindepth", "1", "-printf", "%y\\t%s\\t%T@\\t%m\\t%f\\n"]) .output(); match output { Ok(out) if out.status.success() => { let mut entries: Vec = String::from_utf8_lossy(&out.stdout) .lines() .filter(|l| !l.is_empty()) .map(|line| { let parts: Vec<&str> = line.splitn(5, '\t').collect(); let file_type = parts.first().unwrap_or(&"f"); let size: u64 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); let modified: f64 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0.0); let permissions = parts.get(3).unwrap_or(&""); let name = parts.get(4).unwrap_or(&""); let is_dir = *file_type == "d"; let entry_path = if path.ends_with('/') { format!("{}{}", path, name) } else { format!("{}/{}", path, name) }; serde_json::json!({ "name": name, "path": entry_path, "is_dir": is_dir, "size": if is_dir { 0 } else { size }, "modified": modified as u64, "permissions": permissions, }) }) .collect(); // Sort: directories first, then alphabetically entries.sort_by(|a, b| { let a_dir = a["is_dir"].as_bool().unwrap_or(false); let b_dir = b["is_dir"].as_bool().unwrap_or(false); match (a_dir, b_dir) { (true, false) => std::cmp::Ordering::Less, (false, true) => std::cmp::Ordering::Greater, _ => a["name"].as_str().unwrap_or("") .to_lowercase() .cmp(&b["name"].as_str().unwrap_or("").to_lowercase()), } }); HttpResponse::Ok().json(serde_json::json!({ "path": path, "container": container, "entries": entries, })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to list directory: {}", err.trim()) })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to exec into container: {}", e) })), } } /// POST /api/files/docker/mkdir — create directory inside Docker container pub async fn files_docker_mkdir( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } let output = std::process::Command::new("docker") .args(["exec", container, "mkdir", "-p", path]) .output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Directory created: {}", path) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/docker/delete — delete file/dir inside Docker container pub async fn files_docker_delete( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } let critical = ["/", "/etc", "/usr", "/bin", "/sbin", "/lib", "/boot", "/proc", "/sys", "/dev", "/var"]; if critical.contains(&path) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot delete system directory" })); } let output = std::process::Command::new("docker") .args(["exec", container, "rm", "-rf", path]) .output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Deleted: {}", path) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/docker/rename — rename file/dir inside Docker container pub async fn files_docker_rename( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let from = body.get("from").and_then(|v| v.as_str()).unwrap_or(""); let to = body.get("to").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || from.is_empty() || to.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing fields" })); } let output = std::process::Command::new("docker") .args(["exec", container, "mv", from, to]) .output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Renamed to {}", to) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/files/docker/download?container=ID&path=/file — download file from Docker container pub async fn files_docker_download( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let path = query.get("path").cloned().unwrap_or_default(); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } // docker cp to a temp file, off the async worker: cp of a large // file takes as long as the file is big — running it inline // blocked the event loop for the duration (sync-in-async sweep, // phase 1a). Temp name carries a process-wide counter — the old // pid-only name collided when two downloads ran concurrently. let tmp = unique_tmp_path("wolfstack-docker-dl"); let src = format!("{}:{}", container, path); let tmp_for_cp = tmp.clone(); let output = web::block(move || { std::process::Command::new("docker").args(["cp", &src, &tmp_for_cp]).output() }).await; match output { Ok(Ok(out)) if out.status.success() => { let filename = download_filename(std::path::Path::new(&path)); // Open, then unlink: the open fd keeps the data readable // (POSIX) while the path disappears — no leftover temp file // whether the stream completes or the client disconnects. // NamedFile streams in chunks on the blocking pool instead // of buffering the whole file in RAM like fs::read did. // Open+stat itself offloaded too (open_async is sync // without io-uring). let tmp_c = tmp.clone(); let opened = match web::block(move || actix_files::NamedFile::open(&tmp_c)).await { Ok(r) => r, Err(e) => { let _ = tokio::fs::remove_file(&tmp).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })); } }; match opened { Ok(nf) => { let _ = tokio::fs::remove_file(&tmp).await; nf.set_content_disposition(attachment_disposition(filename)) .into_response(&req) } Err(e) => { let _ = tokio::fs::remove_file(&tmp).await; HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Read error: {}", e) })) } } } Ok(Ok(out)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })), } } /// Collision-proof temp path: pid alone repeats across concurrent /// requests in the same process (two simultaneous downloads corrupted /// each other's temp file before this existed). Lives under a private /// root-owned 0700 dir, NOT world-writable /tmp — a predictable name /// in /tmp is the classic symlink-race target when root writes /// through it (review find, 2026-07-14). fn unique_tmp_path(prefix: &str) -> String { const TMP_DIR: &str = "/var/lib/wolfstack/tmp"; static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static TMP_DIR_READY: std::sync::Once = std::sync::Once::new(); TMP_DIR_READY.call_once(|| { // One mkdir per process lifetime — µs-scale, idempotent. let _ = std::fs::create_dir_all(TMP_DIR); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(TMP_DIR, std::fs::Permissions::from_mode(0o700)); } }); format!( "{}/{}-{}-{}", TMP_DIR, prefix, std::process::id(), TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) ) } /// POST /api/files/docker/upload?container=NAME&path=/some/dir — upload file(s) into a Docker container pub async fn files_docker_upload( req: HttpRequest, state: web::Data, query: web::Query>, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let dir = query.get("path").cloned().unwrap_or_else(|| "/tmp".into()); if container.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })); } use futures::StreamExt; let mut uploaded = Vec::new(); while let Some(Ok(mut field)) = payload.next().await { let filename = field.content_disposition() .and_then(|cd| cd.get_filename().map(|s| s.to_string())) .unwrap_or_else(|| "upload".to_string()); let safe_name = std::path::Path::new(&filename) .file_name() .and_then(|n| n.to_str()) .unwrap_or("upload") .to_string(); if safe_name.is_empty() || safe_name == "." { continue; } // Write to a temp file (async I/O — the old sync writes blocked // the worker per chunk), then docker cp into the container off // the async worker: cp duration scales with file size // (sync-in-async sweep, phase 1a). Unique temp name — pid+name // collided when the same filename uploaded to two containers // concurrently. let tmp = unique_tmp_path("wolfstack-docker-ul"); { let mut file = match tokio::fs::File::create(&tmp).await { Ok(f) => f, Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Cannot create temp file: {}", e) })); } }; use tokio::io::AsyncWriteExt; while let Some(Ok(chunk)) = field.next().await { if file.write_all(&chunk).await.is_err() { let _ = tokio::fs::remove_file(&tmp).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write temp file {}", safe_name) })); } } } let dest = format!("{}:{}/{}", container, dir.trim_end_matches('/'), safe_name); let tmp_for_cp = tmp.clone(); let output = match web::block(move || { std::process::Command::new("docker").args(["cp", &tmp_for_cp, &dest]).output() }).await { Ok(o) => o, Err(e) => { let _ = tokio::fs::remove_file(&tmp).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })); } }; let _ = tokio::fs::remove_file(&tmp).await; match output { Ok(out) if out.status.success() => { uploaded.push(safe_name); } Ok(out) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("docker cp failed: {}", String::from_utf8_lossy(&out.stderr).trim()) })); } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("docker cp error: {}", e) })); } } } HttpResponse::Ok().json(serde_json::json!({ "message": format!("Uploaded {} file(s)", uploaded.len()), "files": uploaded, })) } /// GET /api/files/docker/read?container=ID&path=/etc/hosts — read file from Docker container pub async fn files_docker_read( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = match query.get("container") { Some(c) => c.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })), }; let path = match query.get("path") { Some(p) => p.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let output = std::process::Command::new("docker") .args(["exec", &container, "cat", &path]) .output(); match output { Ok(out) if out.status.success() => { let content = String::from_utf8_lossy(&out.stdout).to_string(); HttpResponse::Ok().json(serde_json::json!({ "path": path, "content": content, "size": content.len() })) } Ok(out) => HttpResponse::BadRequest().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/docker/write — write file inside Docker container pub async fn files_docker_write( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = match body.get("container").and_then(|v| v.as_str()) { Some(c) => c.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })), }; let path = match body.get("path").and_then(|v| v.as_str()) { Some(p) => p.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let content = match body.get("content").and_then(|v| v.as_str()) { Some(c) => c, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'content'" })), }; // Write to temp file then docker cp in let tmp = format!("/tmp/wolfstack-edit-{}", std::process::id()); if let Err(e) = std::fs::write(&tmp, content) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Temp write failed: {}", e) })); } let output = std::process::Command::new("docker") .args(["cp", &tmp, &format!("{}:{}", container, path)]) .output(); let _ = std::fs::remove_file(&tmp); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": "File saved", "path": path })), Ok(out) => HttpResponse::BadRequest().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── LXC File Manager ─── /// Detect if Proxmox `pct` is available, and use `pct exec` if so; else `lxc-attach`. fn lxc_exec_cmd(container: &str, cmd_args: &[&str]) -> std::process::Command { let is_proxmox = std::process::Command::new("which").arg("pct").output() .map(|o| o.status.success()).unwrap_or(false); let mut cmd; if is_proxmox { cmd = std::process::Command::new("pct"); cmd.arg("exec").arg(container).arg("--"); } else { cmd = std::process::Command::new("lxc-attach"); let base = crate::containers::lxc_base_dir(container); if base != crate::containers::LXC_DEFAULT_PATH { cmd.arg("-P").arg(&base); } cmd.arg("-n").arg(container).arg("--"); } for a in cmd_args { cmd.arg(a); } cmd } /// GET /api/files/lxc/browse?container=NAME&path=/ — browse files inside an LXC container pub async fn files_lxc_browse( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let path = query.get("path").cloned().unwrap_or_else(|| "/".into()); if container.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })); } // Use a POSIX shell one-liner that works everywhere (BusyBox, Alpine, Debian, etc.) // Output format per line: TYPESIZENAME // TYPE: d = directory, f = file, l = link let script = format!( "cd '{}' 2>/dev/null && for f in .* *; do [ \"$f\" = '.' ] || [ \"$f\" = '..' ] || [ \"$f\" = '.*' ] || [ \"$f\" = '*' ] && continue; if [ -L \"$f\" ]; then printf 'l\\t0\\t%s\\n' \"$f\"; elif [ -d \"$f\" ]; then printf 'd\\t0\\t%s\\n' \"$f\"; else s=$(stat -c%s \"$f\" 2>/dev/null || echo 0); printf 'f\\t'\"$s\"'\\t%s\\n' \"$f\"; fi; done", path.replace('\'', "'\\''") ); let output = lxc_exec_cmd(&container, &["sh", "-c", &script]).output(); match output { Ok(out) if out.status.success() => { let stdout = String::from_utf8_lossy(&out.stdout); let mut entries: Vec = stdout .lines() .filter(|l| !l.is_empty()) .filter_map(|line| { let parts: Vec<&str> = line.splitn(3, '\t').collect(); if parts.len() < 3 { return None; } let file_type = parts[0]; let size: u64 = parts[1].parse().unwrap_or(0); let name = parts[2].to_string(); if name.is_empty() { return None; } let is_dir = file_type == "d" || file_type == "l"; let entry_path = if path.ends_with('/') { format!("{}{}", path, name) } else { format!("{}/{}", path, name) }; Some(serde_json::json!({ "name": name, "path": entry_path, "is_dir": is_dir, "size": if is_dir { 0 } else { size }, "modified": 0, "permissions": "", })) }) .collect(); entries.sort_by(|a, b| { let a_dir = a["is_dir"].as_bool().unwrap_or(false); let b_dir = b["is_dir"].as_bool().unwrap_or(false); match (a_dir, b_dir) { (true, false) => std::cmp::Ordering::Less, (false, true) => std::cmp::Ordering::Greater, _ => a["name"].as_str().unwrap_or("") .to_lowercase() .cmp(&b["name"].as_str().unwrap_or("").to_lowercase()), } }); HttpResponse::Ok().json(serde_json::json!({ "path": path, "container": container, "entries": entries, })) } Ok(out) => { let err = String::from_utf8_lossy(&out.stderr).to_string(); let _stdout = String::from_utf8_lossy(&out.stdout).to_string(); HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to list directory: {}", err.trim()) })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to exec into container: {}", e) })), } } /// POST /api/files/lxc/mkdir — create directory inside LXC container pub async fn files_lxc_mkdir( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } let output = lxc_exec_cmd(container, &["mkdir", "-p", path]).output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Directory created: {}", path) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/lxc/delete — delete file/dir inside LXC container pub async fn files_lxc_delete( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let path = body.get("path").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } let critical = ["/", "/etc", "/usr", "/bin", "/sbin", "/lib", "/boot", "/proc", "/sys", "/dev", "/var"]; if critical.contains(&path) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot delete system directory" })); } let output = lxc_exec_cmd(container, &["rm", "-rf", path]).output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Deleted: {}", path) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/lxc/rename — rename file/dir inside LXC container pub async fn files_lxc_rename( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = body.get("container").and_then(|v| v.as_str()).unwrap_or(""); let from = body.get("from").and_then(|v| v.as_str()).unwrap_or(""); let to = body.get("to").and_then(|v| v.as_str()).unwrap_or(""); if container.is_empty() || from.is_empty() || to.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing fields" })); } let output = lxc_exec_cmd(container, &["mv", from, to]).output(); match output { Ok(out) if out.status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Renamed to {}", to) })), Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/files/lxc/download?container=NAME&path=/file — download file from LXC container pub async fn files_lxc_download( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let path = query.get("path").cloned().unwrap_or_default(); if container.is_empty() || path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container' or 'path'" })); } // lxc-attach/pct-exec cat, off the async worker — the exec runs as // long as the file is big and blocked the event loop inline // (sync-in-async sweep, phase 1a). Output is still buffered in RAM // (child stdout capture); acceptable for the file-browser use case, // noted in SYNC_ASYNC_SWEEP.md as a potential streaming follow-up. let container_c = container.clone(); let path_c = path.clone(); let output = match web::block(move || { lxc_exec_cmd(&container_c, &["cat", &path_c]).output() }).await { Ok(o) => o, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })), }; match output { Ok(out) if out.status.success() => { let filename = download_filename(std::path::Path::new(&path)); HttpResponse::Ok() .insert_header(attachment_disposition(filename)) .insert_header(("Content-Type", "application/octet-stream")) .body(out.stdout) } Ok(out) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to read file: {}", String::from_utf8_lossy(&out.stderr).trim()) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/lxc/upload?container=NAME&path=/some/dir — upload file(s) into an LXC/Proxmox container pub async fn files_lxc_upload( req: HttpRequest, state: web::Data, query: web::Query>, mut payload: actix_multipart::Multipart, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = query.get("container").cloned().unwrap_or_default(); let dir = query.get("path").cloned().unwrap_or_else(|| "/tmp".into()); if container.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })); } use futures::StreamExt; let mut uploaded = Vec::new(); while let Some(Ok(mut field)) = payload.next().await { let filename = field.content_disposition() .and_then(|cd| cd.get_filename().map(|s| s.to_string())) .unwrap_or_else(|| "upload".to_string()); let safe_name = std::path::Path::new(&filename) .file_name() .and_then(|n| n.to_str()) .unwrap_or("upload") .to_string(); if safe_name.is_empty() || safe_name == "." { continue; } // Write to a temp file with async I/O (the old sync writes ran // on the async worker), then stream it into the container on // the blocking pool. Unique temp name — pid+filename collided // for concurrent same-named uploads. let tmp = unique_tmp_path("wolfstack-lxc-ul"); { let mut file = match tokio::fs::File::create(&tmp).await { Ok(f) => f, Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Cannot create temp file: {}", e) })); } }; use tokio::io::AsyncWriteExt; while let Some(Ok(chunk)) = field.next().await { if file.write_all(&chunk).await.is_err() { let _ = tokio::fs::remove_file(&tmp).await; return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write temp file {}", safe_name) })); } } } // Pipe temp file into the container via tee (works with both // lxc-attach and pct exec). Everything below is blocking — the // spawn, the byte pump, the wait — so the whole unit runs in // web::block. io::copy streams in small chunks: the old path // read the ENTIRE file into RAM (directly under a comment // claiming it avoided exactly that) and pushed it down the // child's stdin with a sync write on the event loop // (sync-in-async sweep, phase 1a). let dest_path = format!("{}/{}", dir.trim_end_matches('/'), safe_name); let container_c = container.clone(); let tmp_c = tmp.clone(); let result: Result, _> = web::block(move || { let mut child = lxc_exec_cmd(&container_c, &["tee", &dest_path]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .spawn() .map_err(|e| format!("Failed to exec into container: {}", e))?; let mut src = std::fs::File::open(&tmp_c) .map_err(|e| format!("Failed to read temp file: {}", e))?; if let Some(ref mut stdin) = child.stdin { std::io::copy(&mut src, stdin) .map_err(|e| format!("Failed to write to container: {}", e))?; } drop(child.stdin.take()); // Close stdin so tee finishes child.wait().map_err(|e| format!("Container exec error: {}", e)) }).await; let _ = tokio::fs::remove_file(&tmp).await; match result { Ok(Ok(status)) if status.success() => { uploaded.push(safe_name); } Ok(Ok(_)) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to upload {} to container", safe_name) })); } Ok(Err(e)) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("blocking pool: {}", e) })); } } } HttpResponse::Ok().json(serde_json::json!({ "message": format!("Uploaded {} file(s)", uploaded.len()), "files": uploaded, })) } /// GET /api/files/lxc/read?container=NAME&path=/etc/hosts — read file from LXC container pub async fn files_lxc_read( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = match query.get("container") { Some(c) => c.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })), }; let path = match query.get("path") { Some(p) => p.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let output = std::process::Command::new("lxc-attach") .args(["-n", &container, "--", "cat", &path]) .output(); match output { Ok(out) if out.status.success() => { let content = String::from_utf8_lossy(&out.stdout).to_string(); HttpResponse::Ok().json(serde_json::json!({ "path": path, "content": content, "size": content.len() })) } Ok(out) => HttpResponse::BadRequest().json(serde_json::json!({ "error": String::from_utf8_lossy(&out.stderr).trim().to_string() })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/files/lxc/write — write file inside LXC container pub async fn files_lxc_write( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_operator_auth(&req, &state) { return e; } let container = match body.get("container").and_then(|v| v.as_str()) { Some(c) => c.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'container'" })), }; let path = match body.get("path").and_then(|v| v.as_str()) { Some(p) => p.to_string(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'path'" })), }; let content = match body.get("content").and_then(|v| v.as_str()) { Some(c) => c, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'content'" })), }; // Write via lxc-attach using tee let mut child = match std::process::Command::new("lxc-attach") .args(["-n", &container, "--", "tee", &path]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .spawn() { Ok(c) => c, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), }; if let Some(mut stdin) = child.stdin.take() { use std::io::Write; let _ = stdin.write_all(content.as_bytes()); } match child.wait() { Ok(status) if status.success() => HttpResponse::Ok().json(serde_json::json!({ "message": "File saved", "path": path })), Ok(_) => HttpResponse::BadRequest().json(serde_json::json!({ "error": "lxc-attach write failed" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/agent/storage/apply — receive and apply a mount config from another node (cluster-auth) pub async fn agent_storage_apply( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_cluster_auth(&req, &state) { return e; } let mut mount = body.into_inner(); // A global NFS mount whose source points at loopback would, replicated // verbatim, make every PEER mount itself — which runs no NFS server, so // it errors on every node but the originator (wabil cluster-NFS, // 2026-06-16). Rewrite a loopback source host to the sending node's // address (the connection source IP — the same req.peer_addr technique // the router replication uses) so peers reach the originator's real // server. Only loopback hosts are touched, and a loopback source can // never work on a peer anyway, so a correctly-addressed mount is never // changed. if matches!(mount.mount_type, storage::MountType::Nfs) && let Some(sender) = req.peer_addr().map(|a| a.ip()) { mount.source = rewrite_loopback_nfs_source(&mount.source, sender); } // Idempotent upsert (NOT create_mount): a re-synced global mount that // already exists on this peer must UPDATE + re-attempt the mount, not // fail with "Mount point already in use" before ever creating the dir or // mounting (wabil 2026-06-16). match storage::apply_replicated_mount(mount) { Ok(m) => HttpResponse::Ok().json(serde_json::json!({ "message": "Mount applied", "mount": m })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Rewrite an NFS source's host to `sender` when it points at loopback /// (`127.0.0.0/8`, `::1`, or `localhost`). NFS sources are `host:/export`; /// splitting on the first `:/` parses bracketed IPv6 (`[::1]:/p`) and IPv4 /// (`1.2.3.4:/p`) alike. Non-loopback sources are returned unchanged. fn rewrite_loopback_nfs_source(source: &str, sender: std::net::IpAddr) -> String { let (host, path) = match source.trim().split_once(":/") { Some((h, p)) => (h, p), None => return source.to_string(), }; let hclean = host.trim().trim_start_matches('[').trim_end_matches(']'); let is_loopback = hclean.eq_ignore_ascii_case("localhost") || hclean.parse::().map(|ip| ip.is_loopback()).unwrap_or(false); if !is_loopback { return source.to_string(); } let new_host = match sender { std::net::IpAddr::V6(_) => format!("[{}]", sender), std::net::IpAddr::V4(_) => sender.to_string(), }; format!("{}:/{}", new_host, path) } /// Helper: push a mount config to all remote cluster nodes async fn sync_mount_to_cluster( state: &web::Data, mount: &storage::StorageMount, ) -> Result, String> { let nodes = state.cluster.get_all_nodes(); let mut results = Vec::new(); for node in &nodes { // Only WolfStack peers run the storage agent; skip self and // Proxmox-only members (they'd just 404). if node.is_self || node.node_type != "wolfstack" { continue; } // Canonical HTTPS-first URL chain. The old code posted a hardcoded // `http://:` — but peers serve HTTPS on that port (the // plaintext second listener was removed), so the request died on the // TLS handshake INSTANTLY on every modern peer. The apply was never // reached: no mount, no dir, and no entry in the peer's Storage // Manager (wabil 2026-06-16). build_node_urls leads with HTTPS, and // API_HTTP_CLIENT already accepts the peers' self-signed certs. let urls = build_node_urls(&node.address, node.port, "/api/agent/storage/apply"); let mut applied = false; let mut last_status = serde_json::Value::from("error"); let mut last_response = String::from("no attempts"); for url in &urls { match API_HTTP_CLIENT.post(url) .peer_auth(&state.cluster_secret) .json(mount) .timeout(std::time::Duration::from_secs(20)) // apply mounts synchronously .send() .await { Ok(resp) => { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); if status.is_success() { results.push(serde_json::json!({ "node": node.hostname, "status": status.as_u16(), "response": body })); applied = true; break; } last_status = serde_json::Value::from(status.as_u16()); last_response = format!("{} -> {}", url, body.chars().take(300).collect::()); } Err(e) => { last_status = serde_json::Value::from("error"); last_response = format!("{} -> transport: {}", url, e); } } } if !applied { results.push(serde_json::json!({ "node": node.hostname, "status": last_status, "response": last_response })); } } Ok(results) } // ─── Config Export / Import ─── /// Build the full config-export bundle. Shared by the HTTP export, the daily /// auto-backup task, and the manual "back up now" action so all three produce /// identical bundles. PVE API credentials are stripped from the node records /// (the bundle is a downloadable / on-disk artifact, not the live 0600 config). pub fn build_config_bundle() -> serde_json::Value { let mut bundle = serde_json::Map::new(); // Helper: read a JSON file and insert into bundle fn read_json_file(path: &str) -> Option { std::fs::read_to_string(path).ok() .and_then(|s| serde_json::from_str(&s).ok()) } // Nodes (cluster links). Strip PVE API credentials before export: // nodes.json is stored mode 0600 precisely because each record can embed a // peer's pve_token / pve_fingerprint, and an export bundle is a file an // operator may hand to support or store off-box. Topology + cluster names // restore fine without them; PVE tokens are re-entered after a restore. if let Some(mut v) = read_json_file("/etc/wolfstack/nodes.json") { if let Some(arr) = v.as_array_mut() { for node in arr.iter_mut() { if let Some(obj) = node.as_object_mut() { obj.remove("pve_token"); obj.remove("pve_fingerprint"); } } } bundle.insert("nodes".into(), v); } // AI config if let Some(v) = read_json_file("/etc/wolfstack/ai-config.json") { bundle.insert("ai_config".into(), v); } // Storage config if let Some(v) = read_json_file("/etc/wolfstack/storage.json") { bundle.insert("storage_config".into(), v); } // Backup config (schedules only — strip entries to keep it small) if let Some(v) = read_json_file("/etc/wolfstack/backups.json") && let Some(obj) = v.as_object() { let mut cleaned = serde_json::Map::new(); if let Some(schedules) = obj.get("schedules") { cleaned.insert("schedules".into(), schedules.clone()); } bundle.insert("backup_config".into(), serde_json::Value::Object(cleaned)); } // IP mappings if let Some(v) = read_json_file(&crate::paths::get().ip_mappings) { bundle.insert("ip_mappings".into(), v); } // PBS config if let Some(v) = read_json_file("/etc/wolfstack/pbs/config.json") { bundle.insert("pbs_config".into(), v); } // Metadata let hostname = hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_else(|_| "unknown".into()); bundle.insert("exported_from".into(), serde_json::Value::String(hostname)); bundle.insert("exported_at".into(), serde_json::Value::String( chrono::Utc::now().to_rfc3339() )); bundle.insert("version".into(), serde_json::Value::String( env!("CARGO_PKG_VERSION").to_string() )); serde_json::Value::Object(bundle) } /// Export all WolfStack configuration as a downloadable JSON file pub async fn config_export( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok() .insert_header(("Content-Type", "application/json")) .insert_header(("Content-Disposition", "attachment; filename=\"wolfstack-config.json\"")) .json(build_config_bundle()) } /// Import WolfStack configuration from a JSON bundle pub async fn config_import( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let bundle = body.into_inner(); let obj = match bundle.as_object() { Some(o) => o, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid config bundle — expected JSON object" })), }; let (imported, errors) = apply_config_bundle(obj, &state); HttpResponse::Ok().json(config_import_summary(imported, errors)) } /// Apply a parsed config bundle to THIS node: merge cluster nodes, overwrite /// the simple config files, and merge backup schedules. Shared by the HTTP /// upload-import (`config_import`) and the restore-from-saved-backup endpoint /// (`config_backup_restore`). Returns (imported_labels, error_labels) so each /// caller can build its own response. Non-destructive: nodes merge, schedules /// merge by id; only the simple settings files are overwritten wholesale. fn apply_config_bundle( obj: &serde_json::Map, state: &web::Data, ) -> (Vec, Vec) { let mut imported = Vec::new(); let mut errors = Vec::new(); // Ensure config dir exists let _ = std::fs::create_dir_all("/etc/wolfstack"); // Import nodes — merge with existing, skip self if let Some(nodes_val) = obj.get("nodes") { match import_nodes(nodes_val, state) { Ok(count) => imported.push(format!("{} nodes", count)), Err(e) => errors.push(format!("nodes: {}", e)), } } // Simple file imports let file_imports = [ ("ai_config", "/etc/wolfstack/ai-config.json", "AI config"), ("storage_config", "/etc/wolfstack/storage.json", "storage config"), ("ip_mappings", "/etc/wolfstack/ip-mappings.json", "IP mappings"), ]; for (key, path, label) in &file_imports { if let Some(val) = obj.get(*key) { match write_json_file(path, val) { Ok(_) => imported.push(label.to_string()), Err(e) => errors.push(format!("{}: {}", label, e)), } } } // Reload AI config into the running agent so changes take effect immediately if obj.contains_key("ai_config") { let reloaded = crate::ai::AiConfig::load(); let mut cfg = state.ai_agent.config.lock().unwrap(); *cfg = reloaded; } // Backup config (schedules only) if let Some(val) = obj.get("backup_config") { // Merge schedules into existing config, keeping existing entries let mut config = backup::load_config(); if let Some(schedules) = val.get("schedules").and_then(|v| v.as_array()) && let Ok(imported_schedules) = serde_json::from_value::>( serde_json::Value::Array(schedules.clone()) ) { let existing_ids: std::collections::HashSet = config.schedules.iter().map(|s| s.id.clone()).collect(); let mut added = 0; for schedule in imported_schedules { if !existing_ids.contains(&schedule.id) { config.schedules.push(schedule); added += 1; } } if let Err(e) = backup::save_config(&config) { errors.push(format!("backup schedules: {}", e)); } else { imported.push(format!("{} backup schedules", added)); } } } // PBS config if let Some(val) = obj.get("pbs_config") { let _ = std::fs::create_dir_all("/etc/wolfstack/pbs"); match write_json_file("/etc/wolfstack/pbs/config.json", val) { Ok(_) => imported.push("PBS config".into()), Err(e) => errors.push(format!("PBS config: {}", e)), } } (imported, errors) } /// Build the JSON response body for an import/restore from its result labels. fn config_import_summary(imported: Vec, errors: Vec) -> serde_json::Value { let summary = if errors.is_empty() { format!("Successfully imported: {}", imported.join(", ")) } else { format!("Imported: {}. Errors: {}", imported.join(", "), errors.join(", ")) }; serde_json::json!({ "message": summary, "imported": imported, "errors": errors, }) } /// Write a serde_json::Value to a file as pretty JSON fn write_json_file(path: &str, val: &serde_json::Value) -> Result<(), String> { if let Some(parent) = std::path::Path::new(path).parent() { std::fs::create_dir_all(parent) .map_err(|e| format!("Failed to create dir: {}", e))?; } let json = serde_json::to_string_pretty(val) .map_err(|e| format!("Failed to serialize: {}", e))?; std::fs::write(path, json) .map_err(|e| format!("Failed to write {}: {}", path, e)) } /// Import nodes into the cluster, merging with existing. Returns count of added nodes. fn import_nodes(nodes_val: &serde_json::Value, state: &web::Data) -> Result { // nodes.json — and therefore the exported bundle's "nodes" — is a JSON // ARRAY of Node (see ClusterState::save_nodes, which serializes // `Vec<&Node>`). The old importer parsed it as a map, so EVERY config // restore failed on nodes with "invalid type: sequence, expected a map". // Accept the array form (the real format); also tolerate a legacy // object/map form so a hand-edited bundle still imports. let import_nodes: Vec = match nodes_val { serde_json::Value::Array(_) => serde_json::from_value(nodes_val.clone()) .map_err(|e| format!("Invalid nodes format: {}", e))?, serde_json::Value::Object(_) => { serde_json::from_value::>(nodes_val.clone()) .map_err(|e| format!("Invalid nodes format: {}", e))? .into_values() .collect() } _ => return Err("expected an array of nodes".to_string()), }; let self_id = state.cluster.self_id.clone(); let mut added = 0; { let mut nodes = state.cluster.nodes_write(); for mut node in import_nodes { // Never import ourselves — match BOTH the local key id and the // global self_id the record carries (the exporting node lists us as // a peer keyed by our ws-{uuid}). if node.id == self_id || node.self_id.as_deref() == Some(self_id.as_str()) { continue; } // Dedup against what we already hold: by local id, by stable global // self_id (when present), or by reachable address+port+type. Mirrors // the convergence dedup so a restore can't create duplicate records. let dup = nodes.values().any(|n| { n.id == node.id || (node.self_id.is_some() && n.self_id == node.self_id) // Include pve_node_name in the address key — a multi-node // Proxmox cluster shares one API endpoint address+port but // has a distinct pve_node_name per node. Omitting it (as the // first cut did) would collapse pve2/pve3 into pve1 and // silently drop them. Mirrors add_server_full's dedup. || (n.address == node.address && n.port == node.port && n.node_type == node.node_type && n.pve_node_name == node.pve_node_name) }); if dup { continue; } node.is_self = false; node.online = false; // re-confirmed on next poll nodes.insert(node.id.clone(), node); added += 1; } } // Persist state.cluster.save_nodes(); Ok(added) } // ─── Automatic config backups ─── // // WolfStack snapshots its whole configuration (cluster nodes + AI / storage / // PBS / IP-mapping settings + backup schedules) to disk once a day, plus on // demand, so a wiped or garbled config can always be restored from // Settings → Config Backup. This is exactly the hole the v24.29.x incident // fell into: the membership list was lost and there was no on-box snapshot to // roll back to. Bundles are written 0600 (they can embed storage / PBS creds) // in a 0700 directory; PVE creds are stripped by build_config_bundle. /// Directory holding on-box config snapshots. fn config_backup_dir() -> &'static str { "/etc/wolfstack/config-backups" } /// How many snapshots to keep — older ones are pruned after each new write. const CONFIG_BACKUP_KEEP: usize = 14; /// Validate a backup filename (a URL path segment) and resolve it INSIDE the /// backup dir. Rejects every path-traversal shape (slashes, `..`, leading dot, /// non-allowlisted chars) so a crafted name can't read/delete arbitrary files. fn safe_backup_path(name: &str) -> Result { if name.is_empty() || name.len() > 128 || name.contains('/') || name.contains('\\') || name.contains("..") || name.starts_with('.') || !name.ends_with(".json") || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') { return Err("invalid backup name".into()); } Ok(std::path::Path::new(config_backup_dir()).join(name)) } /// List saved config backups newest-first: (filename, size_bytes, mtime_secs). fn list_config_backups() -> Vec<(String, u64, u64)> { let mut out: Vec<(String, u64, u64)> = Vec::new(); if let Ok(rd) = std::fs::read_dir(config_backup_dir()) { for entry in rd.flatten() { let name = entry.file_name().to_string_lossy().to_string(); if !(name.starts_with("wolfstack-config-") && name.ends_with(".json")) { continue; } if let Ok(meta) = entry.metadata() { let mtime = meta.modified().ok() .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| d.as_secs()) .unwrap_or(0); out.push((name, meta.len(), mtime)); } } } // Newest first. The timestamped name also sorts chronologically, so it's a // stable tiebreaker when two files share an mtime second. out.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| b.0.cmp(&a.0))); out } /// Delete all but the newest `keep` snapshots. fn prune_config_backups(keep: usize) { for (name, _, _) in list_config_backups().into_iter().skip(keep) { if let Ok(p) = safe_backup_path(&name) { let _ = std::fs::remove_file(p); } } } /// Write the current config bundle to a timestamped snapshot, then prune to /// `CONFIG_BACKUP_KEEP`. Returns the filename written. Sync (file I/O) — call /// via `web::block` / `spawn_blocking` off the async runtime. pub fn write_config_backup_now() -> Result { let dir = config_backup_dir(); std::fs::create_dir_all(dir).map_err(|e| format!("create dir: {}", e))?; // Lock the directory down — snapshots can embed storage / PBS credentials. #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)); } let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string(); let name = format!("wolfstack-config-{}.json", stamp); let path = std::path::Path::new(dir).join(&name); let json = serde_json::to_string_pretty(&build_config_bundle()) .map_err(|e| format!("serialize: {}", e))?; // 0600 — same sensitivity as the live config files it snapshots. crate::paths::write_secure(&path.to_string_lossy(), json) .map_err(|e| format!("write: {}", e))?; prune_config_backups(CONFIG_BACKUP_KEEP); Ok(name) } /// Write a daily snapshot if none exists for today (UTC). Returns the name /// written, or `None` if today's snapshot is already present. Driven by the /// hourly task in main.rs — the per-day guard makes it at-most-once-per-day /// and restart-safe. pub fn maybe_write_daily_config_backup() -> Result, String> { let today = chrono::Utc::now().format("%Y%m%d").to_string(); let prefix = format!("wolfstack-config-{}-", today); if list_config_backups().iter().any(|(n, _, _)| n.starts_with(&prefix)) { return Ok(None); } write_config_backup_now().map(Some) } /// GET /api/config/backups — list saved config snapshots pub async fn config_backups_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let listed = web::block(list_config_backups).await.unwrap_or_default(); let backups: Vec = listed.into_iter() .map(|(name, size, modified)| serde_json::json!({ "name": name, "size": size, "modified": modified, })) .collect(); HttpResponse::Ok().json(serde_json::json!({ "backups": backups })) } /// POST /api/config/backups — create a snapshot now pub async fn config_backup_create(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } match web::block(write_config_backup_now).await { Ok(Ok(name)) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Backup created: {}", name), "name": name, })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "backup task failed" })), } } /// GET /api/config/backups/{name} — download a saved snapshot pub async fn config_backup_download( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let p = match safe_backup_path(&name) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; match web::block(move || std::fs::read(&p)).await { Ok(Ok(bytes)) => HttpResponse::Ok() .insert_header(("Content-Type", "application/json")) // name is allowlisted to [A-Za-z0-9._-] above, so it's safe in the header. .insert_header(("Content-Disposition", format!("attachment; filename=\"{}\"", name))) .body(bytes), _ => HttpResponse::NotFound().json(serde_json::json!({ "error": "backup not found" })), } } /// DELETE /api/config/backups/{name} — delete a saved snapshot pub async fn config_backup_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let p = match safe_backup_path(&name) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; match web::block(move || std::fs::remove_file(&p)).await { Ok(Ok(())) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Deleted {}", name) })), _ => HttpResponse::NotFound().json(serde_json::json!({ "error": "backup not found" })), } } /// POST /api/config/backups/{name}/restore — restore a saved snapshot onto this node pub async fn config_backup_restore( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); let p = match safe_backup_path(&name) { Ok(p) => p, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let data = match web::block(move || std::fs::read_to_string(&p)).await { Ok(Ok(d)) => d, _ => return HttpResponse::NotFound().json(serde_json::json!({ "error": "backup not found" })), }; let bundle: serde_json::Value = match serde_json::from_str(&data) { Ok(v) => v, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("backup is not valid JSON: {}", e) })), }; let obj = match bundle.as_object() { Some(o) => o, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "backup is not a config bundle object" })), }; let (imported, errors) = apply_config_bundle(obj, &state); HttpResponse::Ok().json(config_import_summary(imported, errors)) } /// Path the web-triggered upgrade streams its stdout+stderr to. The /// previous run is overwritten (the most recent failure is what an /// operator wants to inspect; older runs aren't useful). Permissions are /// 0644 so an operator can `cat` it without sudo. NEVER under /var/lib — /// `/var/lib/wolfstack` is on the OnAccessExcludePath list and we want /// this log scannable by clamav. const UPGRADE_LOG_PATH: &str = "/var/log/wolfstack-upgrade.log"; const UPGRADE_LOG_MAX_RETURN_BYTES: usize = 256 * 1024; /// POST /api/upgrade — run the WolfStack upgrade script in the background /// Optional query param: ?channel=beta (defaults to master) pub async fn system_upgrade( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let channel = query.get("channel").map(|s| s.as_str()).unwrap_or("master"); let (branch, flag) = if channel == "beta" { ("beta", " --beta") } else { ("master", "") }; // WolfStack itself runs as root (needs /etc/shadow for auth — see // CLAUDE.md), so the `sudo` that used to live here was redundant // AND broke on minimal Proxmox installs which don't ship sudo by // default (customer report 2026-05-25: NyvenZA's Proxmox box logs // in as root and has no sudo binary, so `curl | sudo bash` errored // with "sudo: command not found"). Pipe straight to bash — we're // already root. // The trailing status line tells a watcher of /api/upgrade/log that the // run ended. Without it a failed run is indistinguishable from a slow // one, and Upgrade All's rolling mode waits on each node in turn. // pipefail so a failed download counts as a failed run. let cmd = format!( "set -o pipefail; curl -sSL https://raw.githubusercontent.com/intelligentwolf/WolfStack/{}/setup.sh | bash -s --{}; \ echo \"=== WolfStack upgrade exited with status $? ===\"", branch, flag ); // Truncate + write a header line so the operator sees what kicked // off this upgrade run even before setup.sh starts producing output. // Then re-open in append mode and hand the file to the child as // stdout+stderr. Previous-run output is discarded on every new // upgrade — the most recent failure is what matters; older runs are // noise. use std::io::Write; { let mut hdr = match std::fs::OpenOptions::new() .create(true).write(true).truncate(true) .open(UPGRADE_LOG_PATH) { Ok(f) => f, Err(e) => { error!("Failed to create upgrade log {}: {}", UPGRADE_LOG_PATH, e); return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to create {}: {}", UPGRADE_LOG_PATH, e) })); } }; let _ = writeln!( hdr, "=== WolfStack upgrade started {} (channel={}, branch={}) ===\n$ {}\n", chrono::Utc::now().to_rfc3339(), channel, branch, cmd, ); // 0644 so the operator can `cat` without sudo; the log doesn't // contain secrets — only setup.sh output and apt progress. #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = hdr.set_permissions(std::fs::Permissions::from_mode(0o644)); } } let log_for_stdout = match std::fs::OpenOptions::new() .append(true).open(UPGRADE_LOG_PATH) { Ok(f) => f, Err(e) => { error!("Failed to reopen upgrade log {} for append: {}", UPGRADE_LOG_PATH, e); return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to open {} for streaming: {}", UPGRADE_LOG_PATH, e) })); } }; let log_for_stderr = match log_for_stdout.try_clone() { Ok(f) => f, Err(e) => { error!("Failed to dup upgrade log fd: {}", e); return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to dup log fd: {}", e) })); } }; // Spawn the upgrade script as a detached background process with // stdout+stderr captured to UPGRADE_LOG_PATH. The child inherits the // file descriptors, so output continues to land even after this // handler returns and the WolfStack binary restarts mid-upgrade // (setup.sh runs as a child of init, file descriptors survive). match std::process::Command::new("bash") .args(["-c", &cmd]) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::from(log_for_stdout)) .stderr(std::process::Stdio::from(log_for_stderr)) .spawn() { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Upgrade started ({} channel) — WolfStack will restart automatically when complete.", branch), "log_path": UPGRADE_LOG_PATH, "log_url": "/api/upgrade/log", })), Err(e) => { error!("Failed to start upgrade: {}", e); // Surface the spawn failure to the log file too so even // a /api/upgrade/log poll sees it. if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(UPGRADE_LOG_PATH) { let _ = writeln!(f, "=== ERROR: failed to spawn upgrade: {} ===", e); } HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to start upgrade: {}", e), "log_path": UPGRADE_LOG_PATH, })) } } } /// GET /api/upgrade/log — return the tail of the upgrade log so the /// operator can see what setup.sh / apt produced without ssh'ing in. /// Returns the LAST `UPGRADE_LOG_MAX_RETURN_BYTES` bytes — big enough /// for a full setup.sh run, small enough that the UI doesn't choke. /// Optional query param `?tail=N` (bytes) overrides, capped at 4 MB. pub async fn system_upgrade_log( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let tail_bytes: usize = query.get("tail") .and_then(|s| s.parse::().ok()) .map(|n| n.min(4 * 1024 * 1024)) .unwrap_or(UPGRADE_LOG_MAX_RETURN_BYTES); let path = std::path::Path::new(UPGRADE_LOG_PATH); if !path.exists() { return HttpResponse::Ok().json(serde_json::json!({ "exists": false, "path": UPGRADE_LOG_PATH, "message": "No upgrade has been run via the web interface on this node yet.", "content": "", "size_bytes": 0, "truncated": false, })); } let size_bytes = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0); let content = match std::fs::read(path) { Ok(bytes) => { let start = bytes.len().saturating_sub(tail_bytes); // UTF-8 boundary safety: if we landed mid-codepoint, walk // forward to the next start byte (top bits 0x.. or 0b10.. // are continuation bytes — skip them). let mut safe_start = start; while safe_start < bytes.len() && (bytes[safe_start] & 0xC0) == 0x80 { safe_start += 1; } String::from_utf8_lossy(&bytes[safe_start..]).to_string() } Err(e) => { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to read {}: {}", UPGRADE_LOG_PATH, e) })); } }; let mtime_rfc3339 = std::fs::metadata(path).ok() .and_then(|m| m.modified().ok()) .map(|t| chrono::DateTime::::from(t).to_rfc3339()); HttpResponse::Ok().json(serde_json::json!({ "exists": true, "path": UPGRADE_LOG_PATH, "content": content, "size_bytes": size_bytes, "truncated": size_bytes > content.len(), "modified_at": mtime_rfc3339, })) } // ─── WolfFlow Workflow Automation API ─── /// GET /api/wolfflow/workflows — list workflows pub async fn wolfflow_list(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = query.get("cluster").map(|s| s.as_str()); HttpResponse::Ok().json(state.wolfflow.list_workflows(cluster)) } /// POST /api/wolfflow/workflows — create workflow pub async fn wolfflow_create(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match serde_json::from_value::(body.into_inner()) { Ok(mut wf) => { if wf.id.is_empty() { wf.id = format!("wf-{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis()); } if wf.created_at.is_empty() { wf.created_at = chrono::Utc::now().to_rfc3339(); } wf.updated_at = chrono::Utc::now().to_rfc3339(); let created = state.wolfflow.create_workflow(wf); HttpResponse::Ok().json(created) } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid workflow: {}", e) })), } } /// GET /api/wolfflow/workflows/{id} pub async fn wolfflow_get(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match state.wolfflow.get_workflow(&path.into_inner()) { Some(wf) => HttpResponse::Ok().json(wf), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Workflow not found" })), } } /// PUT /api/wolfflow/workflows/{id} pub async fn wolfflow_update(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match serde_json::from_value::(body.into_inner()) { Ok(mut wf) => { wf.updated_at = chrono::Utc::now().to_rfc3339(); match state.wolfflow.update_workflow(&path.into_inner(), wf) { Some(updated) => HttpResponse::Ok().json(updated), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Workflow not found" })), } } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid workflow: {}", e) })), } } /// DELETE /api/wolfflow/workflows/{id} pub async fn wolfflow_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match state.wolfflow.delete_workflow(&path.into_inner()) { Some(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Workflow not found" })), } } /// POST /api/wolfflow/workflows/{id}/run — manually trigger a workflow pub async fn wolfflow_trigger(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { // The trigger is not itself a shell sink, but its steps may run // commands on peer nodes, whose exec endpoints demand an operator // attribution — so it takes the operator gate: a real session/API key, // or a node_proxy-forwarded operator ("name (via peer)"). A bare-secret // peer cannot launder a run through here. let actor = match require_operator_auth(&req, &state) { Ok(a) => a, Err(resp) => return resp }; let id = path.into_inner(); let workflow = match state.wolfflow.get_workflow(&id) { Some(wf) => wf, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Workflow not found" })), }; let wf_state = state.wolfflow.clone(); let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); let ai_config = state.ai_agent.config.lock().unwrap().clone(); tokio::spawn(async move { crate::wolfflow::execute_workflow(&wf_state, &cluster, &secret, &actor, &workflow, "manual", Some(ai_config)).await; }); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": "Workflow triggered" })) } /// GET /api/wolfflow/runs — list execution history pub async fn wolfflow_runs_list(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let wf_id = query.get("workflow_id").map(|s| s.as_str()); let limit = query.get("limit").and_then(|s| s.parse().ok()).unwrap_or(50); let mut runs = state.wolfflow.list_runs(wf_id); runs.reverse(); // newest first runs.truncate(limit); HttpResponse::Ok().json(runs) } /// GET /api/wolfflow/runs/{id} pub async fn wolfflow_run_detail(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let runs = state.wolfflow.list_runs(None); match runs.into_iter().find(|r| r.id == id) { Some(run) => HttpResponse::Ok().json(run), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Run not found" })), } } /// GET /api/wolfflow/toolbox — list available actions pub async fn wolfflow_toolbox(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::wolfflow::toolbox_actions()) } /// GET /api/wolfflow/infrastructure — returns the full infrastructure tree for target selection /// Clusters → Nodes → Docker containers, LXC containers, VMs pub async fn wolfflow_infrastructure(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let nodes = state.cluster.get_all_nodes(); let cluster_secret = state.cluster_secret.clone(); let http_client = &*API_HTTP_CLIENT; let mut clusters: std::collections::HashMap> = std::collections::HashMap::new(); for node in &nodes { // Skip legacy Proxmox-API-only entries — they're surfaced via the deprecation banner. if node.node_type == "proxmox" { continue; } let cluster_name = node.cluster_name.clone() .unwrap_or_else(|| "Default".to_string()); let mut node_data = serde_json::json!({ "id": node.id, "hostname": node.hostname, "address": node.address, "port": node.port, "online": node.online, "node_type": node.node_type, "is_self": node.is_self, "docker": [], "lxc": [], "vms": [], }); // Fetch containers for online nodes if node.online && node.node_type == "wolfstack" { let urls = build_node_urls(&node.address, node.port, "/api/containers/docker"); for url in &urls { if let Ok(resp) = http_client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .send().await && let Ok(containers) = resp.json::>().await { node_data["docker"] = serde_json::json!(containers.iter().map(|c| { serde_json::json!({ "name": c.get("name").and_then(|v| v.as_str()).unwrap_or("?"), "state": c.get("state").and_then(|v| v.as_str()).unwrap_or("?"), }) }).collect::>()); break; } } let urls = build_node_urls(&node.address, node.port, "/api/containers/lxc"); for url in &urls { if let Ok(resp) = http_client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .send().await && let Ok(containers) = resp.json::>().await { node_data["lxc"] = serde_json::json!(containers.iter().map(|c| { serde_json::json!({ "name": c.get("name").and_then(|v| v.as_str()).unwrap_or("?"), "state": c.get("state").and_then(|v| v.as_str()).unwrap_or("?"), }) }).collect::>()); break; } } let urls = build_node_urls(&node.address, node.port, "/api/vms"); for url in &urls { if let Ok(resp) = http_client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .send().await && let Ok(vms) = resp.json::>().await { node_data["vms"] = serde_json::json!(vms.iter().map(|v| { serde_json::json!({ "name": v.get("name").and_then(|v| v.as_str()).unwrap_or("?"), "state": if v.get("running").and_then(|v| v.as_bool()).unwrap_or(false) { "running" } else { "stopped" }, }) }).collect::>()); break; } } } else if node.online && node.node_type == "proxmox" { // PVE nodes — fetch guests // PVE guests fetched via the local /pve/resources endpoint below let pve_url = format!("/api/nodes/{}/pve/resources", node.id); if let Ok(resp) = http_client.get(format!("https://{}:{}{}", "127.0.0.1", 8553, pve_url)) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&cluster_secret) .send().await && let Ok(guests) = resp.json::>().await { let lxc: Vec<_> = guests.iter() .filter(|g| g.get("guest_type").and_then(|v| v.as_str()) == Some("lxc")) .map(|g| serde_json::json!({ "name": g.get("name").and_then(|v| v.as_str()).unwrap_or("?"), "state": g.get("status").and_then(|v| v.as_str()).unwrap_or("?"), })) .collect(); let vms: Vec<_> = guests.iter() .filter(|g| g.get("guest_type").and_then(|v| v.as_str()) == Some("qemu")) .map(|g| serde_json::json!({ "name": g.get("name").and_then(|v| v.as_str()).unwrap_or("?"), "state": g.get("status").and_then(|v| v.as_str()).unwrap_or("?"), })) .collect(); node_data["lxc"] = serde_json::json!(lxc); node_data["vms"] = serde_json::json!(vms); } } clusters.entry(cluster_name).or_default().push(node_data); } HttpResponse::Ok().json(clusters) } /// POST /api/wolfflow/exec — execute a single action (used by remote execution) pub async fn wolfflow_exec(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } match serde_json::from_value::(body.into_inner()) { Ok(action) => { match crate::wolfflow::execute_action_local(&action).await { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output })), Err(err) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "output": err })), } } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid action: {}", e) })), } } /// POST /api/wolfflow/container-exec — execute an action inside a specific container (cluster proxy) pub async fn wolfflow_container_exec(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let data = body.into_inner(); let action_val = data.get("action").cloned().unwrap_or(serde_json::Value::Null); let ct_val = data.get("container").cloned().unwrap_or(serde_json::Value::Null); let action: crate::wolfflow::ActionType = match serde_json::from_value(action_val) { Ok(a) => a, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid action: {}", e) })), }; let ct: crate::wolfflow::ContainerTarget = match serde_json::from_value(ct_val) { Ok(c) => c, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid container target: {}", e) })), }; match crate::wolfflow::execute_action_in_container(&action, &ct).await { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output.text })), Err(err) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": err })), } } /// POST /api/wolfflow/all-containers-exec — execute an action inside all containers on this node (cluster proxy) pub async fn wolfflow_all_containers_exec(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } match serde_json::from_value::(body.into_inner()) { Ok(action) => { match crate::wolfflow::execute_in_all_local_containers(&action).await { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output.text })), Err(err) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": err })), } } Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid action: {}", e) })), } } // ─── User Preferences API ─── fn user_prefs_path(username: &str) -> Option { // Sanitize username — no dots (prevents ../ traversal), no slashes let safe: String = username.chars() .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) .collect(); if safe.is_empty() || safe == "cluster-node" { return None; } let path = format!("{}/user-prefs/{}.json", crate::paths::get().config_dir, safe); // Verify the path is under the expected directory let expected_dir = format!("{}/user-prefs/", crate::paths::get().config_dir); if !path.starts_with(&expected_dir) { return None; } Some(path) } /// GET /api/user/preferences — load the current user's preferences pub async fn user_prefs_get(req: HttpRequest, state: web::Data) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_prefs_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; match std::fs::read_to_string(&path) { Ok(data) => { match serde_json::from_str::(&data) { Ok(prefs) => HttpResponse::Ok().json(prefs), Err(_) => HttpResponse::Ok().json(serde_json::json!({})), } } Err(_) => HttpResponse::Ok().json(serde_json::json!({})), } } /// POST /api/user/preferences — save the current user's preferences (full replace) pub async fn user_prefs_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_prefs_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; let dir = std::path::Path::new(&path).parent().unwrap_or(std::path::Path::new("/tmp")); if let Err(e) = std::fs::create_dir_all(dir) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to create dir: {}", e) })); } // Limit size to prevent abuse (64 KB should be plenty for preferences) let json = serde_json::to_string_pretty(&body.into_inner()).unwrap_or_default(); if json.len() > 65536 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Preferences too large (max 64 KB)" })); } match std::fs::write(&path, &json) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save: {}", e) })), } } /// PATCH /api/user/preferences — merge specific keys into existing preferences pub async fn user_prefs_patch(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_prefs_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; let dir = std::path::Path::new(&path).parent().unwrap_or(std::path::Path::new("/tmp")); let _ = std::fs::create_dir_all(dir); // Load existing let mut prefs: serde_json::Map = std::fs::read_to_string(&path) .ok() .and_then(|d| serde_json::from_str(&d).ok()) .unwrap_or_default(); // Merge incoming keys if let Some(obj) = body.as_object() { for (k, v) in obj { if v.is_null() { prefs.remove(k); } else { prefs.insert(k.clone(), v.clone()); } } } let json = serde_json::to_string_pretty(&prefs).unwrap_or_default(); if json.len() > 65536 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Preferences too large" })); } match std::fs::write(&path, &json) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save: {}", e) })), } } /// GET /api/ping — lightweight liveness probe for the frontend connection /// monitor. Auth-required so the client can distinguish three states: 200 = /// reachable + session valid, 401 = reachable but session gone (→ login), /// network error = server unreachable (→ "connection lost" banner). Does no /// work beyond the auth check so it's cheap to poll every few seconds. pub async fn ping(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } /// When this process began serving. Used by /api/ready to report how long the /// daemon has been up, which is what lets a waiting browser avoid reloading /// into a server that is about to bounce again. static PROCESS_START: std::sync::LazyLock = std::sync::LazyLock::new(std::time::Instant::now); /// Start the uptime clock. Must be called once from main() BEFORE the server /// binds: a `LazyLock` initialises on first ACCESS, so without this the first /// /api/ready request would set the clock and every node would for ever report /// an uptime of roughly zero regardless of how long it had been running. pub fn init_process_start() { let _ = *PROCESS_START; } /// GET /api/ready — UNAUTHENTICATED readiness probe. /// /// Deliberately distinct from /api/ping, which requires a session and so cannot /// tell "server is down" from "you are logged out" — that ambiguity is why the /// dashboard's recovery path could not use it and had to probe a static file /// instead. /// /// Note on honesty: this cannot report startup *progress*, because until the /// HTTP listener is bound there is nothing to ask. A browser waiting through a /// restart sees connection-refused, not a phase. The fix for that window is to /// make it short — public-IP detection was moved off the pre-bind path for /// exactly that reason — not to pretend we can narrate it. /// /// `uptime_secs` and `version` are the useful part: a client can wait until the /// daemon has been up long enough to be worth reloading into, and can tell that /// an upgrade actually changed the running version. pub async fn ready() -> HttpResponse { HttpResponse::Ok().json(serde_json::json!({ "ready": true, "version": env!("CARGO_PKG_VERSION"), "uptime_secs": PROCESS_START.elapsed().as_secs(), })) } /// GET /api/cluster/host-agent-hint — when this server runs inside a /// Docker container, detect a WolfStack agent listening on the Docker /// host (klas, 2026-08-11: docker install and the host agent "don't /// talk to each other"). Probes the container's default gateway — the /// host's address on the docker bridge — for the unauthenticated /// `/api/ready` identity endpoint. Detection only: joining still goes /// through the normal Add Server flow with the host's join token + /// admin credentials; nothing is auto-added. pub async fn cluster_host_agent_hint(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let not_detected = || HttpResponse::Ok().json(serde_json::json!({ "detected": false })); if crate::certbot::detect_container_kind() != crate::certbot::ContainerKind::Docker { return not_detected(); } let Some(gw) = default_gateway_ip() else { return not_detected(); }; // Host already in the cluster (under any of its addresses)? Then // there's nothing to hint — the banner would nag forever. Exact // address (or address:port) match — substring containment would // let a node at 110.0.0.10 suppress a hint for gateway 10.0.0.1. let gw_str = gw.to_string(); let gw_matches = |addr: &str| { addr == gw_str || addr.strip_prefix(gw_str.as_str()) .is_some_and(|rest| rest.starts_with(':')) }; if state.cluster.get_all_nodes().iter().any(|n| gw_matches(&n.address)) { return not_detected(); } // Probe the host for WolfStack. Self-signed TLS is the norm for // agent nodes (same posture as inter-node polling). let client = match reqwest::Client::builder() .danger_accept_invalid_certs(true) .connect_timeout(std::time::Duration::from_secs(2)) .timeout(std::time::Duration::from_secs(4)) .build() { Ok(c) => c, Err(_) => return not_detected(), }; for scheme in ["https", "http"] { let url = format!("{}://{}:8553/api/ready", scheme, gw_str); let Ok(resp) = client.get(&url).send().await else { continue }; let Ok(v) = resp.json::().await else { continue }; if v.get("ready").and_then(|r| r.as_bool()) == Some(true) { return HttpResponse::Ok().json(serde_json::json!({ "detected": true, "address": gw_str, "port": 8553, "version": v.get("version").and_then(|s| s.as_str()).unwrap_or(""), })); } } not_detected() } /// The container's default IPv4 gateway from /proc/net/route — inside /// a bridged Docker container this is the host's bridge address /// (172.17.0.1 on the default bridge). Format per route(8)/procfs: /// whitespace-separated columns, Destination and Gateway as /// little-endian hex (00000000 destination = the default route). fn default_gateway_ip() -> Option { parse_default_gateway(&std::fs::read_to_string("/proc/net/route").ok()?) } /// Pure parser half of [`default_gateway_ip`] — unit-tested because /// the little-endian hex encoding is an endianness footgun. fn parse_default_gateway(content: &str) -> Option { for line in content.lines().skip(1) { let cols: Vec<&str> = line.split_whitespace().collect(); if cols.len() < 3 || cols[1] != "00000000" { continue; } let Ok(gw) = u32::from_str_radix(cols[2], 16) else { continue }; if gw == 0 { continue; } // /proc/net/route stores the address little-endian. return Some(std::net::Ipv4Addr::from(gw.swap_bytes().to_be_bytes())); } None } // ─── Home-dashboard widget fetch proxy ─── /// Pooled client for the home-dashboard widget fetch proxy (RSS feeds, /// Open-Meteo weather). Separate from API_HTTP_CLIENT because that client /// is tuned for inter-node calls: it accepts invalid TLS certs (self-signed /// cluster peers) and pins IPv4 — both wrong for arbitrary public endpoints. static DASH_FETCH_CLIENT: std::sync::LazyLock = std::sync::LazyLock::new(|| { reqwest::Client::builder() .connect_timeout(std::time::Duration::from_secs(10)) .pool_idle_timeout(std::time::Duration::from_secs(15)) .pool_max_idle_per_host(2) .redirect(reqwest::redirect::Policy::limited(5)) .user_agent(concat!("WolfStack/", env!("CARGO_PKG_VERSION"))) .build() .unwrap_or_else(|_| reqwest::Client::new()) }); #[derive(Deserialize)] pub struct DashboardFetchQuery { pub url: String, } /// Extract the host portion of an http(s) URL without pulling in the `url` /// crate: strip the scheme, cut the authority at the first `/`, `?` or `#`, /// drop any userinfo, then strip the port (bracket-aware for IPv6 literals). fn dash_fetch_host(url: &str) -> Option { let rest = url.split_once("://")?.1; let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); let host_port = authority.rsplit_once('@').map(|(_, h)| h).unwrap_or(authority); let host = if let Some(stripped) = host_port.strip_prefix('[') { stripped.split(']').next().unwrap_or("") } else { host_port.split(':').next().unwrap_or("") }; if host.is_empty() { None } else { Some(host.to_ascii_lowercase()) } } /// GET /api/dashboard/fetch-proxy?url=… — server-side fetch for home-dashboard /// widgets (RSS feeds, Open-Meteo weather/geocoding). Exists because most /// third-party feeds send no CORS headers, so the browser cannot fetch them /// directly from the dashboard origin. /// /// Guard rails: /// - Auth required. Reaching internal hosts through this is equivalent to what /// an authenticated operator can already do via status-page monitors and /// webhook targets, so no additional network allow-list is applied. /// - http/https only, 15s total deadline, response capped at 1 MiB. /// - The body is ALWAYS returned as `text/plain` + `nosniff`, never the /// upstream content type — otherwise navigating to this URL with an /// attacker-chosen `url` would render arbitrary HTML under our origin. pub async fn dashboard_fetch_proxy( req: HttpRequest, state: web::Data, q: web::Query, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let url = q.url.trim(); if !(url.starts_with("http://") || url.starts_with("https://")) { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "Only http:// and https:// URLs can be fetched" })); } // Defence-in-depth: refuse link-local IP literals (169.254.0.0/16 — the // cloud metadata range — and IPv6 fe80::/10). No real RSS feed or weather // API lives there, and it keeps this endpoint from becoming a metadata- // credential oracle on cloud-hosted nodes. Loopback and RFC1918 stay // reachable ON PURPOSE: homelab operators legitimately point the RSS // widget at LAN services (FreshRSS, a local Grafana), and an // authenticated WolfStack operator already has a full host console, so // blocking private ranges would cost real functionality without removing // any capability. Hostnames are not resolved here — this is a tripwire // for the common probe, not a DNS-rebinding-proof boundary. let host = match dash_fetch_host(url) { Some(h) => h, None => { return HttpResponse::BadRequest() .json(serde_json::json!({ "error": "URL has no host" })); } }; let link_local = host.parse::().ok().map(|ip| match ip { std::net::IpAddr::V4(v4) => v4.is_link_local(), // fe80::/10 — first 10 bits 1111 1110 10 std::net::IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80, }).unwrap_or(false); if link_local { return HttpResponse::Forbidden() .json(serde_json::json!({ "error": "Link-local addresses cannot be fetched" })); } const MAX_BYTES: usize = 1024 * 1024; let mut resp = match DASH_FETCH_CLIENT .get(url) .timeout(std::time::Duration::from_secs(15)) .send() .await { Ok(r) => r, Err(e) => { return HttpResponse::BadGateway() .json(serde_json::json!({ "error": format!("Fetch failed: {e}") })); } }; let status = resp.status(); if !status.is_success() { return HttpResponse::BadGateway() .json(serde_json::json!({ "error": format!("Upstream returned HTTP {}", status.as_u16()) })); } let mut body: Vec = Vec::new(); loop { match resp.chunk().await { Ok(Some(chunk)) => { if body.len() + chunk.len() > MAX_BYTES { return HttpResponse::BadGateway() .json(serde_json::json!({ "error": "Response exceeds the 1 MiB proxy limit" })); } body.extend_from_slice(&chunk); } Ok(None) => break, Err(e) => { return HttpResponse::BadGateway() .json(serde_json::json!({ "error": format!("Read failed: {e}") })); } } } HttpResponse::Ok() .insert_header(("X-Content-Type-Options", "nosniff")) .content_type("text/plain; charset=utf-8") .body(body) } // ─── Per-user interface lock (idle lock + PIN) ─── // // A soft, client-enforced screen lock: after `idle_minutes` of inactivity // the dashboard covers itself and asks for a PIN. This is a "stop a random // passer-by getting into an unattended session" deterrent, NOT a hard // access control — a technical user with devtools can bypass a client-side // overlay. The PIN itself, though, is treated as a credential: it's stored // only as a salted SHA-256 hash in a per-user file that the prefs GET never // returns, and it's verified server-side with a small delay on failure to // slow guessing. The watchful eye of the lock — like Durin's Gate, it opens // only to the one who knows the word. /// Per-user lock profile path. Separate from `user_prefs_path` so the PIN /// hash is never served by the preferences GET. Same sanitisation + /// traversal guard as the prefs path. fn user_lock_path(username: &str) -> Option { let safe: String = username.chars() .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) .collect(); if safe.is_empty() || safe == "cluster-node" { return None; } let path = format!("{}/user-prefs/{}.lock.json", crate::paths::get().config_dir, safe); let expected_dir = format!("{}/user-prefs/", crate::paths::get().config_dir); if !path.starts_with(&expected_dir) { return None; } Some(path) } #[derive(serde::Serialize, serde::Deserialize, Default)] struct UserLockProfile { #[serde(default)] enabled: bool, #[serde(default)] idle_minutes: u32, #[serde(default)] pin_salt: String, #[serde(default)] pin_hash: String, } fn load_user_lock(path: &str) -> UserLockProfile { std::fs::read_to_string(path).ok() .and_then(|d| serde_json::from_str(&d).ok()) .unwrap_or_default() } /// Salted SHA-256 of the PIN. Salt is per-PIN-set, so the same PIN on two /// accounts (or reset on the same account) yields a different hash. fn hash_user_pin(salt: &str, pin: &str) -> String { use sha2::Digest; let digest = sha2::Sha256::digest(format!("{}:{}", salt, pin).as_bytes()); digest.iter().map(|b| format!("{:02x}", b)).collect() } fn random_lock_salt() -> String { use rand::RngCore; let mut bytes = [0u8; 16]; rand::thread_rng().fill_bytes(&mut bytes); bytes.iter().map(|b| format!("{:02x}", b)).collect() } /// Constant-time comparison so a failed verify doesn't leak how many /// leading hex chars matched via timing. fn ct_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } let mut diff = 0u8; for (x, y) in a.iter().zip(b.iter()) { diff |= x ^ y; } diff == 0 } /// GET /api/user/lock — the current user's idle-lock settings. Never /// returns the salt or hash; `pin_set` is the only PIN signal. pub async fn user_lock_get(req: HttpRequest, state: web::Data) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_lock_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; let lock = load_user_lock(&path); HttpResponse::Ok().json(serde_json::json!({ "username": username, "enabled": lock.enabled, "idle_minutes": if lock.idle_minutes == 0 { 10 } else { lock.idle_minutes }, "pin_set": !lock.pin_hash.is_empty(), })) } #[derive(serde::Deserialize)] pub struct UserLockUpdate { enabled: Option, idle_minutes: Option, /// `Some(non-empty)` sets a new PIN; `Some("")` clears it; `None` leaves /// the existing PIN untouched. pin: Option, } /// POST /api/user/lock — update idle-lock settings and/or the PIN. pub async fn user_lock_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_lock_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; if let Some(dir) = std::path::Path::new(&path).parent() { let _ = std::fs::create_dir_all(dir); } let mut lock = load_user_lock(&path); let update = body.into_inner(); if let Some(en) = update.enabled { lock.enabled = en; } if let Some(m) = update.idle_minutes { lock.idle_minutes = m.clamp(1, 240); } match update.pin.as_deref() { Some(p) if !p.is_empty() => { if p.len() < 4 || p.len() > 12 || !p.chars().all(|c| c.is_ascii_digit()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "PIN must be 4–12 digits" })); } let salt = random_lock_salt(); lock.pin_hash = hash_user_pin(&salt, p); lock.pin_salt = salt; } Some(_) => { // Explicit empty string = clear the PIN. Without a PIN there's // nothing to unlock with, so the lock must also turn off. lock.pin_hash.clear(); lock.pin_salt.clear(); lock.enabled = false; } None => {} } // Can't arm a lock with no PIN to unlock it. if lock.enabled && lock.pin_hash.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Set a PIN before enabling the lock" })); } if lock.idle_minutes == 0 { lock.idle_minutes = 10; } let json = serde_json::to_string_pretty(&lock).unwrap_or_default(); match std::fs::write(&path, &json) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "enabled": lock.enabled, "idle_minutes": lock.idle_minutes, "pin_set": !lock.pin_hash.is_empty(), })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save: {}", e) })), } } /// POST /api/user/lock/verify — check a PIN to lift the lock. Returns /// `{ ok: bool }`. A 300 ms delay on failure rate-limits brute force. pub async fn user_lock_verify(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let username = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let path = match user_lock_path(&username) { Some(p) => p, None => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "Not a user account" })), }; let lock = load_user_lock(&path); // No PIN configured → nothing to verify against, treat as unlocked. if lock.pin_hash.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "ok": true })); } let pin = body.get("pin").and_then(|v| v.as_str()).unwrap_or(""); let candidate = hash_user_pin(&lock.pin_salt, pin); let ok = ct_eq(candidate.as_bytes(), lock.pin_hash.as_bytes()); if !ok { // Async sleep — never block the runtime thread (see CLAUDE.md). tokio::time::sleep(std::time::Duration::from_millis(300)).await; } HttpResponse::Ok().json(serde_json::json!({ "ok": ok })) } // ─── WolfUSB API ─── /// GET /api/wolfusb/status — wolfusb availability, config, assignments pub async fn wolfusb_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfusb::WolfUsbConfig::load(); let available = crate::wolfusb::is_wolfusb_available(); let version = if available { crate::wolfusb::get_wolfusb_version() } else { None }; let kmod = crate::wolfusb::kernel_module_status(); HttpResponse::Ok().json(serde_json::json!({ "wolfusb_available": available, "enabled": config.enabled, "assignment_count": config.assignments.len(), "version": version, "kernel_modules": { "vhci_hcd_loaded": kmod.vhci_hcd_loaded, "usbip_host_loaded": kmod.usbip_host_loaded, "fully_ready": kmod.is_fully_ready(), "install_hint": kmod.install_hint, }, })) } /// POST /api/wolfusb/install — install wolfusb tools pub async fn wolfusb_install(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::wolfusb::install_wolfusb().await { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": output })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), } } /// GET /api/wolfusb/config — get config pub async fn wolfusb_get_config(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfusb::WolfUsbConfig::load(); HttpResponse::Ok().json(&config) } /// POST /api/wolfusb/config — save config and sync to cluster pub async fn wolfusb_save_config(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::wolfusb::WolfUsbConfig::load(); if let Some(v) = body.get("enabled").and_then(|v| v.as_bool()) { config.enabled = v; } match config.save() { Ok(_) => { wolfusb_broadcast_sync(&state); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Broadcast WolfUSB assignments to all cluster nodes fn wolfusb_broadcast_sync(state: &web::Data) { let config = crate::wolfusb::WolfUsbConfig::load(); let cluster_secret = state.cluster_secret.clone(); let nodes = state.cluster.get_all_nodes(); let client = API_HTTP_CLIENT.clone(); let payload = serde_json::json!({ "assignments": config.assignments }); for node in nodes.iter().filter(|n| !n.is_self && n.online) { let urls = crate::api::build_node_urls(&node.address, node.port, "/api/wolfusb/sync"); let secret = cluster_secret.clone(); let body = payload.clone(); let c = client.clone(); tokio::spawn(async move { for url in &urls { if c.post(url) .peer_auth(&secret) .json(&body) .timeout(std::time::Duration::from_secs(5)) .send() .await .is_ok() { break; } } }); } } /// GET /api/wolfusb/devices — list USB devices on this node pub async fn wolfusb_devices(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfusb::WolfUsbConfig::load(); let (devices, wolfusb_working) = crate::wolfusb::list_local_devices_with_status(&config); HttpResponse::Ok().json(serde_json::json!({ "devices": devices, "assignments": config.assignments, "wolfusb_working": wolfusb_working, })) } /// Pick the first non-loopback, non-wildcard IPv4 address on this host. /// Used to fill in the self-node's connectable address when nodes.json has /// it stored as a bind wildcard (0.0.0.0), which isn't routable from peers. fn pick_routable_address() -> Option { // Try tailscale first since wolfstack clusters usually use it. if let Ok(out) = std::process::Command::new("tailscale").arg("ip").arg("-4").output() && out.status.success() { let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); if !s.is_empty() && !s.starts_with("127.") { return Some(s.lines().next().unwrap_or("").to_string()); } } // Fall back to `ip -4 route get 1.1.1.1` to find the egress interface's IP. if let Ok(out) = std::process::Command::new("ip") .args(["-4", "route", "get", "1.1.1.1"]) .output() && out.status.success() { let s = String::from_utf8_lossy(&out.stdout); if let Some(src) = s.split("src ").nth(1) { let addr = src.split_whitespace().next().unwrap_or(""); if !addr.is_empty() && !addr.starts_with("127.") { return Some(addr.to_string()); } } } None } /// GET /api/wolfusb/cluster_devices — aggregate USB devices from every node. /// Users pick the device they want and the target they want in one view; the /// backend records the real source node automatically, no matter which node's /// dashboard they're looking at. pub async fn wolfusb_cluster_devices( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Skip nodes that are known-offline (last heartbeat > 5 min). The // cluster state can retain stale entries for nodes that were removed, // renamed, or permanently taken offline; querying them produces // spurious "Unreachable" warnings for nodes that aren't part of the // cluster anymore. We don't trust Node.online alone because it can // be stuck on True if the polling loop never managed to contact the // node to mark it false. let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let nodes: Vec<_> = state .cluster .get_all_nodes() .into_iter() .filter(|n| n.is_self || (n.online && now.saturating_sub(n.last_seen) < 300)) .collect(); let config = crate::wolfusb::WolfUsbConfig::load(); let secret = state.cluster_secret.clone(); let client = API_HTTP_CLIENT.clone(); // Collect the local node's devices first. let (local_devices, local_ok) = crate::wolfusb::list_local_devices_with_status(&config); let mut out: Vec = Vec::new(); for node in &nodes { let entry = if node.is_self { // If the self node's stored address is a bind wildcard (0.0.0.0 // or ::) it's not connectable from other nodes — pick the first // routable IP we can find so the assignment's source_address // is usable when a remote node tries to mount from us. let advertised_address = if node.address == "0.0.0.0" || node.address == "::" || node.address.is_empty() { pick_routable_address().unwrap_or_else(|| node.address.clone()) } else { node.address.clone() }; serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": advertised_address, "is_self": true, "reachable": true, "wolfusb_working": local_ok, "devices": local_devices, }) } else { // Remote node — fetch via inter-node endpoint using cluster secret. let urls = build_node_urls(&node.address, node.port, "/api/wolfusb/devices"); let mut remote_devices: Vec = Vec::new(); let mut reachable = false; let mut wolfusb_working = false; for url in &urls { match client .get(url) .peer_auth(&secret) .timeout(std::time::Duration::from_secs(5)) .send() .await { Ok(resp) if resp.status().is_success() => { if let Ok(j) = resp.json::().await { remote_devices = j .get("devices") .and_then(|v| v.as_array()) .cloned() .unwrap_or_default(); wolfusb_working = j .get("wolfusb_working") .and_then(|v| v.as_bool()) .unwrap_or(false); reachable = true; break; } } _ => {} } } serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "address": node.address, "is_self": false, "reachable": reachable, "wolfusb_working": wolfusb_working, "devices": remote_devices, }) }; out.push(entry); } HttpResponse::Ok().json(serde_json::json!({ "nodes": out, "assignments": config.assignments, })) } /// POST /api/wolfusb/assign — assign a USB device to a container/VM (cluster-wide) pub async fn wolfusb_assign(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::wolfusb::WolfUsbConfig::load(); let busid = body.get("busid").and_then(|v| v.as_str()).unwrap_or(""); let label = body.get("label").and_then(|v| v.as_str()).unwrap_or(""); let usb_id = body.get("usb_id").and_then(|v| v.as_str()).unwrap_or(""); let source_node_id = body.get("source_node_id").and_then(|v| v.as_str()).unwrap_or(""); let source_hostname = body.get("source_hostname").and_then(|v| v.as_str()).unwrap_or(""); let source_address = body.get("source_address").and_then(|v| v.as_str()).unwrap_or(""); let target_type = body.get("target_type").and_then(|v| v.as_str()).unwrap_or(""); let target_name = body.get("target_name").and_then(|v| v.as_str()).unwrap_or(""); let target_node_id = body.get("target_node_id").and_then(|v| v.as_str()).unwrap_or(""); let target_hostname = body.get("target_hostname").and_then(|v| v.as_str()).unwrap_or(""); if busid.is_empty() || target_type.is_empty() || target_name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "busid, target_type, and target_name are required" })); } // Determine if this node is the source let self_node = state.cluster.get_all_nodes().into_iter().find(|n| n.is_self); let self_id = self_node.as_ref().map(|n| n.id.as_str()).unwrap_or(""); let is_local_source = source_node_id == self_id || source_node_id.is_empty(); // Use WolfNet IP if available, otherwise the regular address let effective_address = if !source_address.is_empty() { source_address.to_string() } else { self_node.as_ref().map(|n| n.address.clone()).unwrap_or_default() }; let effective_source_id = if source_node_id.is_empty() { self_id } else { source_node_id }; match crate::wolfusb::assign_device(&mut config, crate::wolfusb::DeviceAssignmentRequest { busid, label, usb_id, source_node_id: effective_source_id, source_hostname, source_address: &effective_address, target_type, target_name, target_node_id, target_hostname, is_local_source, }) { Ok(msg) => { wolfusb_broadcast_sync(&state); // Trigger the actual mount+passthrough. Four cases: // 1. source=self, target=self → assign_device already did local_passthrough // 2. source=self, target=remote → nothing to mount here; target pulls from us // 3. source=remote, target=self → WE need to mount the remote device here // 4. source=remote, target=remote → forward to target to do case 3 let is_local_target = target_node_id == self_id || target_node_id.is_empty(); let is_cross_node_source = !is_local_source && !effective_address.is_empty(); if is_local_target && is_cross_node_source { // Case 3: we're the target and the source is elsewhere. Run // attach_and_passthrough locally so the wolfusb-mount@ unit // gets installed, enabled, started, and the device gets // passed into the LXC/Docker/VM target. Query the source // for its (bus, addr) first — the target doesn't have the // physical device on its own sysfs, so a local lookup // would return None and the install_mount_unit step would // fail with "not currently attached on this host". let src_addr = effective_address.clone(); let busid_s = busid.to_string(); let target_type_s = target_type.to_string(); let target_name_s = target_name.to_string(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { let sba = query_source_bus_addr(&src_addr, &busid_s, &secret).await; let src_addr_c = src_addr.clone(); let busid_c = busid_s.clone(); let tt = target_type_s.clone(); let tn = target_name_s.clone(); let res = tokio::task::spawn_blocking(move || { crate::wolfusb::attach_and_passthrough(&src_addr_c, &busid_c, &tt, &tn, sba) }).await; match res { Ok(Ok(m)) => tracing::info!("WolfUSB: local attach done — {}", m), Ok(Err(e)) => tracing::warn!("WolfUSB: local attach failed — {}", e), Err(e) => tracing::warn!("WolfUSB: attach task join error — {}", e), } }); } else if !is_local_target && !target_node_id.is_empty() { // Case 4: target is a different node — forward the attach call. // Resolve by either id form (map-key or canonical self_id) so a // frontend-supplied ws-… id still matches a peer keyed under a // node-… map key. Raw n.id== scans miss the self_id form. if let Some(target_node) = state.cluster.get_node(target_node_id) { let urls = crate::api::build_node_urls(&target_node.address, target_node.port, "/api/wolfusb/attach"); let secret = state.cluster_secret.clone(); let client = API_HTTP_CLIENT.clone(); let body = serde_json::json!({ "source_address": effective_address, "busid": busid, "target_type": target_type, "target_name": target_name, }); tokio::spawn(async move { for url in &urls { match client.post(url) .peer_auth(&secret) .json(&body) .timeout(std::time::Duration::from_secs(30)) .send() .await { Ok(resp) if resp.status().is_success() => { tracing::info!("WolfUSB: remote attach triggered on target node"); break; } Ok(resp) => { tracing::warn!("WolfUSB: remote attach returned {}", resp.status()); } Err(e) => { tracing::warn!("WolfUSB: remote attach failed ({}): {}", url, e); } } } }); } } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg })) } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), } } /// POST /api/wolfusb/unassign — remove a USB device assignment pub async fn wolfusb_unassign(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::wolfusb::WolfUsbConfig::load(); let busid = body.get("busid").and_then(|v| v.as_str()).unwrap_or(""); let source_node_id = body.get("source_node_id").and_then(|v| v.as_str()).unwrap_or(""); match crate::wolfusb::unassign_device(&mut config, busid, source_node_id) { Ok(msg) => { wolfusb_broadcast_sync(&state); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg })) } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), } } /// POST /api/wolfusb/sync — receive assignment list from a cluster node (merge into local config) pub async fn wolfusb_sync(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let assignments: Vec = body.get("assignments") .and_then(|v| serde_json::from_value(v.clone()).ok()) .unwrap_or_default(); crate::wolfusb::merge_remote_assignments(&assignments); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } /// POST /api/wolfusb/attach — attach a remote USB device and pass into container (called on target node). /// Queries the SOURCE's `/api/wolfusb/prepare-for-export` first so it /// can learn the source-side (bus, addr) — the target's own sysfs /// doesn't have the device yet, so a local lookup would fail with /// "not currently attached" the way it does in the Re-attach dialog. pub async fn wolfusb_attach(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let source_address = body.get("source_address").and_then(|v| v.as_str()).unwrap_or("").to_string(); let busid = body.get("busid").and_then(|v| v.as_str()).unwrap_or("").to_string(); let target_type = body.get("target_type").and_then(|v| v.as_str()).unwrap_or("").to_string(); let target_name = body.get("target_name").and_then(|v| v.as_str()).unwrap_or("").to_string(); if source_address.is_empty() || busid.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "source_address and busid required" })); } // Ask source for bus+addr. Each attempted URL scheme in turn; any // HTTP success with a parseable bus_addr wins. let source_bus_addr = query_source_bus_addr(&source_address, &busid, &state.cluster_secret).await; // attach_and_passthrough shells out (systemctl, lsusb) and waits up to ~20s // for the virtual device to appear — offload to the blocking pool so it // never ties up an actix worker thread (coding canon: no sync blocking work // in an async handler). spawn_blocking matches the local path in // wolfusb_assign and gives the long (20s) wait ample pool headroom. let bus_addr_resolved = source_bus_addr.is_some(); let busid_c = busid.clone(); let res = tokio::task::spawn_blocking(move || { crate::wolfusb::attach_and_passthrough(&source_address, &busid_c, &target_type, &target_name, source_bus_addr) }).await; match res { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "message": msg, "bus_addr_resolved": bus_addr_resolved })), Ok(Err(e)) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": format!("attach task failed: {}", e) })), } } /// Fetch the SOURCE node's (bus, addr) for a given busid via its /// prepare-for-export endpoint. Returns None if the source is /// unreachable, doesn't know about the busid, or is running an older /// version that doesn't include bus_addr in the response — callers /// then fall back to local sysfs lookup (which works for same-node /// attach and post-reboot vhci-survived attachments). async fn query_source_bus_addr(source_address: &str, busid: &str, secret: &str) -> Option<(u8, u8)> { let urls = build_node_urls(source_address, 8553, "/api/wolfusb/prepare-for-export"); let client = &*API_HTTP_CLIENT; let body = serde_json::json!({ "busid": busid }); for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(secret) .json(&body) .send().await { if !resp.status().is_success() { let _ = resp.bytes().await; continue; } let Ok(v) = resp.json::().await else { continue; }; let Some(arr) = v.get("bus_addr").and_then(|x| x.as_array()) else { continue; }; if arr.len() != 2 { continue; } let b = arr[0].as_u64().and_then(|n| u8::try_from(n).ok()); let a = arr[1].as_u64().and_then(|n| u8::try_from(n).ok()); if let (Some(b), Some(a)) = (b, a) { return Some((b, a)); } } } None } /// GET /api/wolfusb/diagnose/{busid} — read-only walk of the /// passthrough chain for one assignment. Returns an ordered list of /// {step, ok, detail} so the UI can render a top-to-bottom checklist. /// No side effects — safe to call on a cron or from an on-page refresh. pub async fn wolfusb_diagnose( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let busid = path.into_inner(); let steps = crate::wolfusb::diagnose(&busid); let overall_ok = steps.iter().all(|s| s.ok); HttpResponse::Ok().json(serde_json::json!({ "busid": busid, "ok": overall_ok, "steps": steps, })) } /// POST /api/wolfusb/prepare-for-export — called on the SOURCE node /// (the one with the physical USB device) by a TARGET node that's /// about to attach. Idempotent; ensures wolfusb-server is running, /// confirms the device is on the host bus, confirms usbip-host kernel /// module is loaded. Returns the checklist so the caller can surface /// failures to the user before attempting attach. pub async fn wolfusb_prepare_for_export( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let busid = body.get("busid").and_then(|v| v.as_str()).unwrap_or("").to_string(); if busid.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "busid required" })); } let busid_c = busid.clone(); let steps = tokio::task::spawn_blocking(move || { crate::wolfusb::prepare_for_export(&busid_c) }).await.unwrap_or_else(|e| vec![crate::wolfusb::ReattachStep { step: "prepare-for-export task".into(), ok: false, detail: format!("task panicked: {}", e), }]); // Also return the SOURCE's current (bus, addr) so a cross-node // target can build its `wolfusb mount --bus N --addr M` command // without having to look the device up on its own sysfs (where // it doesn't exist yet). let bus_addr = tokio::task::spawn_blocking(move || { crate::wolfusb::bus_addr_for(&busid) }).await.ok().flatten(); let overall_ok = steps.iter().all(|s| s.ok); HttpResponse::Ok().json(serde_json::json!({ "ok": overall_ok, "steps": steps, "bus_addr": bus_addr.map(|(b, a)| serde_json::json!([b, a])), })) } /// POST /api/wolfusb/reattach/{busid} — full recovery flow. /// /// Call from any node the operator is logged into. We look up the /// assignment's target node and proxy to it if we're not that node. /// On the target we: /// 1. (if cross-node) Call source's /api/wolfusb/prepare-for-export /// so the device is unbound locally and ready for usbip-host /// to claim it. /// 2. Run wolfusb::reattach_local which wipes any stale mount unit /// and re-runs the attach chain. /// Returns the combined step list so the UI shows everything that /// happened — this is the UI for fixing Papa's "migration orphaned /// my USB" scenario without SSHing into nodes. pub async fn wolfusb_reattach( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let busid = path.into_inner(); // Look up the assignment to find source + target. let config = crate::wolfusb::WolfUsbConfig::load(); let assignment = config.assignments.iter().find(|a| a.busid == busid).cloned(); let Some(a) = assignment else { return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("no assignment for busid {}", busid), })); }; let self_id = crate::agent::self_node_id(); // Step A: if target is not us, proxy to target and let THEY run // the recovery. Keeps all the node-local kernel/systemd work on // the node that actually needs it. // // Failures on this path return a `steps: [...]` shape (not a bare // `error`) so the UI's per-step renderer has something to draw // instead of the generic "No step data returned" fallback. The // single step describes exactly which proxy hop failed and why, // which is the information the operator actually needs. if a.target_node_id != self_id { // Resolve by either id form (map-key `id` or canonical `self_id`) — see // the source-lookup note below; the same id-form drift breaks the target // hop when the assignment stored the canonical self_id. let Some(target) = state.cluster.get_node(&a.target_node_id) else { return HttpResponse::Ok().json(serde_json::json!({ "ok": false, "steps": [{ "step": "Locate target node", "ok": false, "detail": format!( "Target node {} is not in this cluster's membership. \ The VM may have been migrated away from it, or the \ node was removed. Try running Re-attach from a node \ that currently sees {} as a cluster peer.", a.target_node_id, a.target_node_id ), }], })); }; let urls = build_node_urls(&target.address, target.port, &format!("/api/wolfusb/reattach/{}", urlencoding_simple(&busid))); let client = &*API_HTTP_CLIENT; let mut last_err = String::new(); for url in &urls { let res = client.post(url) .timeout(std::time::Duration::from_secs(60)) .peer_auth(&state.cluster_secret) .send().await; match res { Ok(r) if r.status().is_success() => { let body = r.bytes().await.unwrap_or_default(); return HttpResponse::Ok() .content_type("application/json") .body(body); } Ok(r) => { // Upstream returned a non-2xx — this usually means // the cluster-secret didn't match or the target has // auth misconfigured. Wrap in a step so the UI can // show it clearly instead of dumping raw bytes. let code = r.status().as_u16(); let body_text = r.bytes().await .ok() .and_then(|b| String::from_utf8(b.to_vec()).ok()) .unwrap_or_default(); let trimmed = body_text.chars().take(400).collect::(); return HttpResponse::Ok().json(serde_json::json!({ "ok": false, "steps": [{ "step": format!("Proxy to target {} (HTTP {})", target.hostname, code), "ok": false, "detail": format!( "The target node returned HTTP {}. Common cause: \ cluster-secret mismatch between this node and {}. \ Workaround: open WolfStack directly on {} and click \ Re-attach there.\n\nUpstream body: {}", code, target.hostname, target.hostname, trimmed ), }], })); } Err(e) => { last_err = format!("{} → {}", url, e); continue; } } } return HttpResponse::Ok().json(serde_json::json!({ "ok": false, "steps": [{ "step": format!("Proxy to target {}", target.hostname), "ok": false, "detail": format!( "Could not reach {} on any of the attempted URLs. Check \ that the target node is online (Datacenter page shows \ its state) and that this node's cluster secret matches \ {}'s. Workaround: open WolfStack directly on {} and \ click Re-attach there.\n\nLast error: {}", target.hostname, target.hostname, target.hostname, last_err ), }], })); } // Step B: we ARE the target. If cross-node, ask source to prepare // for export first. Accumulate the source's steps into the result // AND extract its (bus, addr) so we can build a valid mount unit // without trying to look the device up on our own sysfs (where it // doesn't exist — it's on the source's bus). let mut all_steps: Vec = Vec::new(); let mut source_bus_addr: Option<(u8, u8)> = None; if a.source_node_id != self_id { // Resolve the source by EITHER id form — the local map-key `id` OR the // canonical `self_id` — via get_node, then fall back to the address // stored on the assignment when the node isn't in cluster gossip at all. // Why both matter: the frontend stores whichever id it displayed (usually // the canonical `ws-…` self_id), while a peer's LOCAL map key is a // `node-…` uuid, so a raw `n.id == source_node_id` scan silently misses // it — that was PapaSchlumpf's "source node ws-aa8c09ff not in cluster" // on a reboot (2026-07-01), even though the source was fully reachable. // And `source_address` is proven-good — the mount unit itself connects to // it — so even a genuinely-absent node id must not block re-attach. let source = match resolve_target_node( &state, &a.source_node_id, (!a.source_address.is_empty()).then_some(a.source_address.as_str()), Some(8553), ) { Some(n) => n, None => { all_steps.push(crate::wolfusb::ReattachStep { step: "Locate source node".into(), ok: false, detail: format!( "source node {} not in cluster and the assignment has no \ stored source address — check node membership", a.source_node_id ), }); return HttpResponse::Ok().json(serde_json::json!({ "ok": false, "steps": all_steps })); } }; let urls = build_node_urls(&source.address, source.port, "/api/wolfusb/prepare-for-export"); let client = &*API_HTTP_CLIENT; let body = serde_json::json!({ "busid": busid }); let mut source_reached = false; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&state.cluster_secret) .json(&body) .send().await { if resp.status().is_success() { source_reached = true; if let Ok(v) = resp.json::().await { if let Some(arr) = v.get("steps").and_then(|s| s.as_array()) { for step in arr { all_steps.push(crate::wolfusb::ReattachStep { step: format!("[{}] {}", source.hostname, step.get("step").and_then(|x| x.as_str()).unwrap_or("?")), ok: step.get("ok").and_then(|x| x.as_bool()).unwrap_or(false), detail: step.get("detail").and_then(|x| x.as_str()).unwrap_or("").to_string(), }); } } // [bus, addr] — optional; new in v18.7.21. // Older sources don't include the field, which // leaves source_bus_addr as None and the target // falls back to local sysfs (the old broken // behaviour, but no regression). if let Some(arr) = v.get("bus_addr").and_then(|x| x.as_array()) && arr.len() == 2 { let b = arr[0].as_u64().and_then(|n| u8::try_from(n).ok()); let a_ = arr[1].as_u64().and_then(|n| u8::try_from(n).ok()); if let (Some(b), Some(a_)) = (b, a_) { source_bus_addr = Some((b, a_)); } } } break; } else { let _ = resp.bytes().await; } } } if !source_reached { all_steps.push(crate::wolfusb::ReattachStep { step: "Contact source node".into(), ok: false, detail: format!( "Could not reach {} on any URL — check the node is online and \ cluster-secret auth is working.", source.hostname ), }); return HttpResponse::Ok().json(serde_json::json!({ "ok": false, "steps": all_steps })); } } // Step C: run the local reattach — cleans stale mount unit and // reruns attach_and_passthrough. spawn_blocking because it shells // systemctl + wolfusb. source_bus_addr plumbs the source's real // bus+addr through to install_mount_unit so the unit's ExecStart // can correctly pass `--bus N --addr M` to wolfusb mount. let busid_c = busid.clone(); let source_bus_addr_c = source_bus_addr; let local_steps = tokio::task::spawn_blocking(move || { crate::wolfusb::reattach_local(&busid_c, source_bus_addr_c) }).await.unwrap_or_else(|e| vec![crate::wolfusb::ReattachStep { step: "local reattach task".into(), ok: false, detail: format!("task panicked: {}", e), }]); all_steps.extend(local_steps); let overall_ok = all_steps.iter().all(|s| s.ok); HttpResponse::Ok().json(serde_json::json!({ "busid": busid, "ok": overall_ok, "steps": all_steps, })) } // ─── MySQL Database Editor API ─── /// GET /api/mysql/detect — check if MySQL is installed on this node pub async fn mysql_detect( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } HttpResponse::Ok().json(crate::mysql_editor::detect_mysql()) } /// GET /api/mysql/detect-containers — find MySQL/MariaDB in Docker/LXC containers pub async fn mysql_detect_containers( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let containers = crate::mysql_editor::detect_mysql_containers(); HttpResponse::Ok().json(serde_json::json!({ "containers": containers })) } #[derive(Deserialize)] pub struct MysqlConnectRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } fn mysql_default_port() -> u16 { 3306 } /// POST /api/mysql/connect — test a database connection (MySQL or PostgreSQL) pub async fn mysql_connect( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: None, db_type: body.db_type, }; let result = if body.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(10), crate::mysql_editor::pg_test_connection(¶ms)).await } else { tokio::time::timeout(std::time::Duration::from_secs(10), crate::mysql_editor::test_connection(¶ms)).await }; match result { Ok(Ok(version)) => { HttpResponse::Ok().json(serde_json::json!({ "connected": true, "version": version, })) } Ok(Err(e)) => { HttpResponse::Ok().json(serde_json::json!({ "connected": false, "error": e, })) } Err(_) => { HttpResponse::Ok().json(serde_json::json!({ "connected": false, "error": format!("Connection to {}:{} timed out after 10 seconds.", body.host, body.port), })) } } } #[derive(Deserialize)] pub struct MysqlCredsRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, #[serde(default)] pub database: Option, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } impl MysqlCredsRequest { fn to_params(&self) -> crate::mysql_editor::ConnParams { crate::mysql_editor::ConnParams { host: self.host.clone(), port: self.port, user: self.user.clone(), password: self.password.clone(), database: self.database.clone(), db_type: self.db_type, } } } /// POST /api/mysql/databases — list databases pub async fn mysql_databases( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = body.to_params(); let result = if params.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(15), crate::mysql_editor::pg_list_databases(¶ms)).await } else { tokio::time::timeout(std::time::Duration::from_secs(15), crate::mysql_editor::list_databases(¶ms)).await }; match result { Ok(Ok(dbs)) => HttpResponse::Ok().json(serde_json::json!({ "databases": dbs })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Database list request timed out after 15 seconds" })), } } #[derive(Deserialize)] pub struct MysqlTablesRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, pub database: String, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } /// POST /api/mysql/tables — list tables in a database pub async fn mysql_tables( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: Some(body.database.clone()), db_type: body.db_type, }; let db = body.database.clone(); let result = if body.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(15), crate::mysql_editor::pg_list_tables(¶ms, &db)).await } else { tokio::time::timeout(std::time::Duration::from_secs(15), crate::mysql_editor::list_tables(¶ms, &db)).await }; match result { Ok(Ok(tables)) => HttpResponse::Ok().json(serde_json::json!({ "tables": tables })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Table list timed out" })), } } #[derive(Deserialize)] pub struct MysqlStructureRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, pub database: String, pub table: String, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } /// POST /api/mysql/structure — get table structure pub async fn mysql_structure( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: Some(body.database.clone()), db_type: body.db_type, }; let db = body.database.clone(); let tbl = body.table.clone(); let result = if body.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(15), crate::mysql_editor::pg_table_structure(¶ms, &db, &tbl)).await } else { tokio::time::timeout(std::time::Duration::from_secs(15), async { crate::mysql_editor::table_structure(¶ms, &db, &tbl).await .map(serde_json::Value::Array) }).await }; match result { Ok(Ok(cols)) => HttpResponse::Ok().json(serde_json::json!({ "columns": cols })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Structure request timed out" })), } } #[derive(Deserialize)] pub struct MysqlDataRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, pub database: String, pub table: String, #[serde(default)] pub page: u64, #[serde(default = "mysql_default_page_size")] pub page_size: u64, #[serde(default)] pub order_by: Option, #[serde(default)] pub order_dir: Option, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } fn mysql_default_page_size() -> u64 { 50 } /// POST /api/mysql/data — get paginated table data pub async fn mysql_data( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: Some(body.database.clone()), db_type: body.db_type, }; let db = body.database.clone(); let tbl = body.table.clone(); let page = body.page; let page_size = body.page_size; let order_by = body.order_by.clone(); let order_dir = body.order_dir.clone(); let ob = order_by.as_deref(); let od = order_dir.as_deref(); let result = if body.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(30), crate::mysql_editor::pg_table_data(¶ms, &db, &tbl, page as u32, page_size as u32, ob, od)).await } else { tokio::time::timeout(std::time::Duration::from_secs(30), crate::mysql_editor::table_data(¶ms, &db, &tbl, page, page_size, ob, od)).await }; match result { Ok(Ok(data)) => HttpResponse::Ok().json(data), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Data request timed out" })), } } #[derive(Deserialize)] pub struct MysqlQueryRequest { pub host: String, #[serde(default = "mysql_default_port")] pub port: u16, pub user: String, #[serde(default)] pub password: String, #[serde(default)] pub database: String, pub query: String, #[serde(default)] pub db_type: crate::mysql_editor::DbType, } /// POST /api/mysql/query — execute arbitrary SQL pub async fn mysql_query( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: if body.database.is_empty() { None } else { Some(body.database.clone()) }, db_type: body.db_type, }; let db = body.database.clone(); let query = body.query.clone(); let result = if body.db_type == crate::mysql_editor::DbType::Postgres { tokio::time::timeout(std::time::Duration::from_secs(30), crate::mysql_editor::pg_execute_query(¶ms, &db, &query)).await } else { tokio::time::timeout(std::time::Duration::from_secs(30), crate::mysql_editor::execute_query(¶ms, &db, &query)).await }; match result { Ok(Ok(result)) => HttpResponse::Ok().json(result), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Query timed out" })), } } #[derive(Deserialize)] pub struct MysqlDumpRequest { pub host: String, pub port: u16, pub user: String, pub password: String, pub database: String, pub include_data: bool, } /// POST /api/mysql/dump — dump database to SQL pub async fn mysql_dump( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let params = crate::mysql_editor::ConnParams { host: body.host.clone(), port: body.port, user: body.user.clone(), password: body.password.clone(), database: Some(body.database.clone()), db_type: crate::mysql_editor::DbType::Mysql, // dump is MySQL-only for now }; let result = tokio::time::timeout( std::time::Duration::from_secs(120), crate::mysql_editor::dump_database(¶ms, &body.database, body.include_data), ).await; match result { Ok(Ok(sql)) => { let filename = format!("{}{}.sql", body.database, if body.include_data { "_full" } else { "_structure" }); HttpResponse::Ok() .content_type("application/sql") .insert_header(("Content-Disposition", format!("attachment; filename=\"{}\"", filename))) .body(sql) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": "Dump timed out after 120 seconds" })), } } // ─── App Store ─── /// GET /api/appstore/apps?q=&category= — list/search available apps pub async fn appstore_list( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let q = query.get("q").map(|s| s.as_str()); let cat = query.get("category").map(|s| s.as_str()); let apps = appstore::list_apps(q, cat); // Annotate each app with `compose_available` so the install modal // can show the Docker Compose option without a second lookup. // Computed from the manifest already in hand (handcrafted template // or any Docker target — resolve_compose_template's exact // semantics): the old has_compose_template call here rebuilt the // ENTIRE catalogue per app, 534 rebuilds per request, which // blocked the async worker for seconds on small ARM boards. let annotated: Vec = apps.iter().map(|app| { let mut obj = match serde_json::to_value(app) { Ok(serde_json::Value::Object(m)) => m, _ => serde_json::Map::new(), }; let compose_available = appstore::handcrafted_compose_template(&app.id).is_some() || app.docker.is_some(); obj.insert("compose_available".to_string(), serde_json::Value::Bool(compose_available)); serde_json::Value::Object(obj) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "apps": annotated })) } /// GET /api/appstore/apps/{id} — get app details. The response body /// is the manifest plus a computed `compose_available` flag so the /// install wizard can show or hide the Docker Compose option without /// a second round-trip. pub async fn appstore_get( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match appstore::get_app(&id) { Some(app) => { let compose_available = appstore::has_compose_template(&app.id); let mut obj = match serde_json::to_value(&app) { Ok(serde_json::Value::Object(m)) => m, _ => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": "manifest serialisation" })), }; obj.insert("compose_available".to_string(), serde_json::Value::Bool(compose_available)); HttpResponse::Ok().json(serde_json::Value::Object(obj)) } None => HttpResponse::NotFound().json(serde_json::json!({ "error": format!("App '{}' not found", id) })), } } #[derive(Deserialize)] pub struct AppInstallRequest { pub target: String, // "docker", "lxc", "bare" pub container_name: String, // name for the container #[serde(default)] pub inputs: std::collections::HashMap, // user input values #[serde(default)] pub storage_path: Option, // optional storage location #[serde(default)] pub ports: Option>, // optional custom port mappings (overrides manifest) #[serde(default)] pub extra_env: Option>, // additional env vars (KEY=VALUE) #[serde(default)] pub extra_volumes: Option>, // additional volume mounts (host:container) #[serde(default)] pub memory_limit: Option, // e.g. "512m", "2g" #[serde(default)] pub cpu_limit: Option, // e.g. "0.5", "2" /// Deployment mode for Docker target. "docker-run" (default, /// existing behaviour) or "docker-compose" (opt-in, requires the /// manifest to ship a compose template). Missing from older /// clients ⇒ docker-run, so nothing breaks. #[serde(default)] pub deployment_type: Option, } /// POST /api/appstore/apps/{id}/install — install an app pub async fn appstore_install( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // Block raw Docker/LXC installs on nodes running Kubernetes (server or worker) if matches!(body.target.as_str(), "docker" | "lxc") && (!crate::kubernetes::list_clusters().is_empty() || !crate::kubernetes::detect_existing_clusters().is_empty()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "This node runs Kubernetes — use WolfKube to deploy applications instead of raw Docker/LXC" })); } let mut inputs = body.inputs.clone(); // Inject CONTAINER_NAME for ${CONTAINER_NAME} substitution in manifests inputs.insert("CONTAINER_NAME".to_string(), body.container_name.clone()); let custom_ports = body.ports.clone(); match appstore::install_app( &id, &body.target, &body.container_name, &inputs, custom_ports.as_deref(), body.deployment_type.as_deref(), ) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/appstore/installed/{install_id}/compose.yaml — read the /// rendered compose file for a compose-backed install. Returns /// text/yaml so the frontend can drop the body straight into an editor. pub async fn appstore_compose_get( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let install_id = path.into_inner(); match appstore::read_compose_file(&install_id) { Ok(yaml) => HttpResponse::Ok() .content_type("text/yaml; charset=utf-8") .body(yaml), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct AppComposeWriteRequest { pub content: String, } /// PUT /api/appstore/installed/{install_id}/compose.yaml — overwrite /// the compose file and run `docker compose up -d` to apply the new /// definition. The stack's containers are recreated by compose as /// needed. pub async fn appstore_compose_put( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let install_id = path.into_inner(); match appstore::write_compose_file(&install_id, &body.content) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// POST /api/system/prepare-install-package — write a shell script that /// installs a single OS package (currently just the mount-helper packages /// nfs-common / cifs-utils) and return a session_id the UI opens as a /// live-terminal console so the user can watch the install run. #[derive(Deserialize)] pub struct PreparePkgInstallRequest { /// One of the `mount.*` binaries the user needs — e.g. "mount.cifs". pub binary: String, } pub async fn prepare_install_package( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (pkg_mgr, pkg_name) = match crate::storage::package_for_helper(&body.binary) { Some(v) => v, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("No known package provides '{}'", body.binary) })), }; let session_id = format!("pkg-{}-{}", pkg_name, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) .unwrap_or_default().as_secs() ); let script_path = format!("/tmp/wolfstack-pkginstall-{}.sh", session_id); // Escaped script; `-y` so apt/dnf/zypper don't block on confirmation, // and `--noconfirm` for pacman. set -e so the first failure stops the // run instead of muddying the terminal with cascaded errors. let install_cmd = match pkg_mgr { "apt-get" => format!("apt-get update && apt-get install -y {}", pkg_name), // s3fs-fuse is an EPEL package on RHEL-likes — without the repo the // install fails with a bare "No match for argument". // `|| true` because the script runs under `set -e` and epel-release // is absent on Fedora (where s3fs-fuse is in the main repo anyway). "dnf" if pkg_name == "s3fs-fuse" => format!("dnf install -y epel-release || true; dnf install -y {}", pkg_name), "dnf" => format!("dnf install -y {}", pkg_name), "zypper" => format!("zypper --non-interactive install {}", pkg_name), "pacman" => format!("pacman -Sy --noconfirm {}", pkg_name), "apk" => format!("apk add --no-cache {}", pkg_name), other => format!("{} install -y {}", other, pkg_name), }; let script = format!( "#!/bin/bash\nset -e\n\ printf '\\033[1;36m━━━ Installing %s (provides %s) ━━━\\033[0m\\n\\n' '{pkg}' '{bin}'\n\ {cmd}\n\ printf '\\n\\033[1;32m✓ %s installed\\033[0m\\n' '{pkg}'\n", pkg = pkg_name, bin = body.binary, cmd = install_cmd ); if let Err(e) = std::fs::write(&script_path, script) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write install script: {}", e) })); } let _ = std::process::Command::new("chmod").args(["+x", &script_path]).output(); HttpResponse::Ok().json(serde_json::json!({ "session_id": session_id, "package": pkg_name, "command": install_cmd, })) } /// POST /api/appstore/apps/{id}/install-stream — VM-target streaming install /// Emits progress lines as Server-Sent Events so the UI can show download /// bytes / elapsed time / stage transitions in a task-log entry instead of /// freezing on a single blocking POST for several minutes. pub async fn appstore_install_stream( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let app_id = path.into_inner(); let Some(app) = appstore::get_app(&app_id) else { return HttpResponse::NotFound().json(serde_json::json!({"error": format!("App '{}' not found", app_id)})); }; if app.vm.is_none() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "This app has no VM target"})); } let mut inputs = body.inputs.clone(); inputs.insert("CONTAINER_NAME".to_string(), body.container_name.clone()); let container_name = body.container_name.clone(); // std::sync::mpsc because install_vm_streamed runs in a blocking thread // and needs a Send Sender. Bridge to tokio so the SSE stream can await. let (std_tx, std_rx) = std::sync::mpsc::channel::(); let (tok_tx, mut tok_rx) = tokio::sync::mpsc::channel::(256); // Worker: do the install, close the channel when done. std::thread::spawn(move || { let result = appstore::install_vm_streamed(&app, &container_name, &inputs, std_tx.clone()); // Final marker — success or error, both go through the stream. match result { Ok(msg) => { let _ = std_tx.send(format!("[done] {}", msg)); } Err(e) => { let _ = std_tx.send(format!("[error] {}", e)); } } // std_tx dropping here signals EOF to the bridge. }); // Bridge blocking recv() -> tokio channel. tokio::task::spawn_blocking(move || { while let Ok(msg) = std_rx.recv() { if tok_tx.blocking_send(msg).is_err() { break; } } }); let stream = async_stream::stream! { while let Some(msg) = tok_rx.recv().await { // Embed as SSE data. Newlines inside a message get mapped to // `\ndata: ` so the client sees a single event with multi-line // body; keeps any future multi-line messages intact. let event = format!("data: {}\n\n", msg.replace('\n', "\ndata: ")); yield Ok::<_, actix_web::Error>(actix_web::web::Bytes::from(event)); } }; HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) // identity encoding so the Compress middleware leaves this stream // alone — gzip-ing an SSE stream buffers it and breaks the live // progress/console output the UI relies on. .insert_header(("Content-Encoding", "identity")) .insert_header(("Cache-Control", "no-cache")) .insert_header(("Connection", "keep-alive")) .insert_header(("X-Accel-Buffering", "no")) .streaming(stream) } /// POST /api/appstore/apps/{id}/prepare-install — generate install script for live terminal pub async fn appstore_prepare_install( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // Block raw Docker/LXC installs on nodes running Kubernetes (server or worker) if matches!(body.target.as_str(), "docker" | "lxc") && (!crate::kubernetes::list_clusters().is_empty() || !crate::kubernetes::detect_existing_clusters().is_empty()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "This node runs Kubernetes — use WolfKube to deploy applications instead of raw Docker/LXC" })); } let mut inputs = body.inputs.clone(); inputs.insert("CONTAINER_NAME".to_string(), body.container_name.clone()); let target = body.target.clone(); let container_name = body.container_name.clone(); let storage_path = body.storage_path.clone(); let custom_ports = body.ports.clone(); let extra_env = body.extra_env.clone(); let extra_volumes = body.extra_volumes.clone(); let memory_limit = body.memory_limit.clone(); let cpu_limit = body.cpu_limit.clone(); match web::block(move || { appstore::prepare_install(appstore::PrepareInstallOptions { app_id: &id, target: &target, container_name: &container_name, user_inputs: &inputs, storage_path: storage_path.as_deref(), custom_ports: custom_ports.as_deref(), extra_env: extra_env.as_deref(), extra_volumes: extra_volumes.as_deref(), memory_limit: memory_limit.as_deref(), cpu_limit: cpu_limit.as_deref(), }) }).await { Ok(Ok((session_id, _script_path))) => HttpResponse::Ok().json(serde_json::json!({ "session_id": session_id, })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Internal error: {}", e) })), } } /// GET /api/appstore/installed — list installed apps pub async fn appstore_installed( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let apps = appstore::list_installed_apps(); HttpResponse::Ok().json(serde_json::json!({ "installed": apps })) } /// DELETE /api/appstore/installed/{id} — uninstall an app pub async fn appstore_uninstall( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let install_id = path.into_inner(); match appstore::uninstall_app(&install_id) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Kubernetes ─── /// GET /api/kubernetes/clusters pub async fn k8s_list_clusters(req: HttpRequest, state: web::Data) -> HttpResponse { // `require_auth` returns the caller principal. "cluster-node" means // another WolfStack node is calling us — in that case we MUST NOT // fan out to peers again, because that peer's handler then fans // back to us, which fans out again, recursive amplification. // Only UI session callers trigger the cluster-wide aggregation. // // Reported by Bel (v19.9.1): three-node cluster spent 70% CPU each // doing 2100 connect()/sec to peer :8553/:8554, traced to this // endpoint via perf (51% of CPU in k8s_list_clusters::{{closure}} // → reqwest send → connect). Every remote_future here calls the // same path on the peer, which re-runs this handler, which // fans out again. Classic mutual recursion across the cluster. let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let from_peer = caller == "cluster-node"; let self_id = state.cluster.self_id.clone(); // Get local clusters and tag with owner_node_id let mut all_clusters: Vec = crate::kubernetes::list_clusters() .into_iter() .map(|mut c| { if c.owner_node_id.is_empty() { c.owner_node_id = self_id.clone(); } c }) .collect(); // Short-circuit for inter-node calls — return LOCAL clusters only. // The UI on the originating node is responsible for aggregating // results from every peer via its own fan-out. if from_peer { return HttpResponse::Ok().json(all_clusters); } // Aggregate clusters from remote WolfStack nodes — UI-originated only. let nodes = state.cluster.get_all_nodes(); let cluster_secret = state.cluster_secret.clone(); let mut remote_futures = Vec::new(); for node in &nodes { if node.is_self || node.node_type != "wolfstack" { continue; } let node_id = node.id.clone(); let urls = build_node_urls(&node.address, node.port, "/api/kubernetes/clusters"); let secret = cluster_secret.clone(); remote_futures.push(async move { let client = &*API_HTTP_CLIENT; for url in &urls { if let Ok(resp) = client.get(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .send() .await { if resp.status().is_success() { if let Ok(mut clusters) = resp.json::>().await { for c in &mut clusters { c.owner_node_id = node_id.clone(); } return clusters; } } else { let _ = resp.bytes().await; } break; // got a response (even if error), don't try other URL schemes } } Vec::new() }); } let results = futures::future::join_all(remote_futures).await; let local_ids: std::collections::HashSet = all_clusters.iter().map(|c| c.id.clone()).collect(); for remote_clusters in results { for c in remote_clusters { if !local_ids.contains(&c.id) { all_clusters.push(c); } } } HttpResponse::Ok().json(all_clusters) } /// GET /api/kubernetes/detect — detect existing k8s installations on this node pub async fn k8s_detect(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let detected = crate::kubernetes::detect_existing_clusters(); let already_registered = crate::kubernetes::list_clusters(); let results: Vec = detected.into_iter() .filter(|(_, path, _)| !already_registered.iter().any(|c| c.kubeconfig_path == *path)) .map(|(name, path, cluster_type)| { serde_json::json!({ "name": name, "kubeconfig_path": path, "cluster_type": cluster_type.to_string() }) }) .collect(); HttpResponse::Ok().json(results) } /// POST /api/kubernetes/clusters — import a cluster via kubeconfig content or path #[derive(Deserialize)] pub struct K8sImportRequest { pub name: String, #[serde(default)] pub kubeconfig: String, // raw kubeconfig YAML content (for pasted imports) #[serde(default)] pub kubeconfig_path: Option, // path to existing kubeconfig (for auto-detected imports) #[serde(default)] pub cluster_type: Option, } pub async fn k8s_create_cluster(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = format!("k8s-{}", body.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-")); // If a path is provided directly (e.g. auto-detected k3s), use it as-is // Otherwise save the pasted kubeconfig content to a file let (kubeconfig_path, kubeconfig_content) = if let Some(ref path) = body.kubeconfig_path { if !std::path::Path::new(path).exists() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Kubeconfig file not found: {}", path) })); } let content = std::fs::read_to_string(path).unwrap_or_default(); (path.clone(), content) } else if !body.kubeconfig.is_empty() { let dir = "/etc/wolfstack/kubernetes"; let _ = std::fs::create_dir_all(dir); let path = format!("{}/{}.yaml", dir, id); // Kubeconfig carries the cluster CA cert and a bearer token // with (typically) full cluster-admin rights. Even though // /etc/wolfstack is now 0700, belt-and-braces: write the file // itself as 0600 so a later accidental dir-perm loosening // doesn't leak admin credentials to local users. if let Err(e) = crate::paths::write_secure(&path, &body.kubeconfig) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to save kubeconfig: {}", e) })); } (path, body.kubeconfig.clone()) } else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Either kubeconfig content or kubeconfig_path is required" })); }; // Try to extract API URL from kubeconfig let api_url = kubeconfig_content.lines() .find(|l| l.trim().starts_with("server:")) .map(|l| l.trim().trim_start_matches("server:").trim().to_string()) .unwrap_or_default(); let cluster_type = match body.cluster_type.as_deref() { Some("k3s") => crate::kubernetes::K8sClusterType::K3s, Some("micro_k8s" | "microk8s") => crate::kubernetes::K8sClusterType::MicroK8s, Some("k0s") => crate::kubernetes::K8sClusterType::K0s, Some("rke2") => crate::kubernetes::K8sClusterType::Rke2, Some("eks") => crate::kubernetes::K8sClusterType::Eks, Some("gke") => crate::kubernetes::K8sClusterType::Gke, Some("aks") => crate::kubernetes::K8sClusterType::Aks, _ => crate::kubernetes::K8sClusterType::K8s, }; match crate::kubernetes::add_cluster(id, body.name.clone(), kubeconfig_path, api_url, cluster_type) { Ok(cluster) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("Cluster '{}' imported", body.name), "cluster": cluster })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/kubernetes/clusters/{id} pub async fn k8s_delete_cluster(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match crate::kubernetes::remove_cluster(&id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": "Cluster removed" })), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/status pub async fn k8s_cluster_status(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; HttpResponse::Ok().json(crate::kubernetes::get_cluster_status(&cluster.kubeconfig_path)) } /// GET /api/kubernetes/clusters/{id}/namespaces pub async fn k8s_namespaces(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; HttpResponse::Ok().json(crate::kubernetes::get_namespaces(&cluster.kubeconfig_path)) } /// POST /api/kubernetes/clusters/{id}/namespaces #[derive(Deserialize)] pub struct K8sNameRequest { pub name: String } pub async fn k8s_create_namespace(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match crate::kubernetes::create_namespace(&cluster.kubeconfig_path, &body.name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/kubernetes/clusters/{id}/namespaces/{name} pub async fn k8s_delete_namespace(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match crate::kubernetes::delete_namespace(&cluster.kubeconfig_path, &name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/pods?namespace= pub async fn k8s_pods(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").filter(|s| !s.is_empty()).map(|s| s.as_str()); HttpResponse::Ok().json(crate::kubernetes::get_pods(&cluster.kubeconfig_path, ns)) } /// DELETE /api/kubernetes/clusters/{id}/pods/{name}?namespace= pub async fn k8s_delete_pod(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::delete_pod(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/deployments?namespace= pub async fn k8s_deployments(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").filter(|s| !s.is_empty()).map(|s| s.as_str()); HttpResponse::Ok().json(crate::kubernetes::get_deployments(&cluster.kubeconfig_path, ns)) } /// DELETE /api/kubernetes/clusters/{id}/deployments/{name}?namespace= pub async fn k8s_delete_deployment(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::delete_deployment(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// PATCH /api/kubernetes/clusters/{id}/deployments/{name}/scale #[derive(Deserialize)] pub struct K8sScaleRequest { pub namespace: String, pub replicas: u32 } pub async fn k8s_scale_deployment(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match crate::kubernetes::scale_deployment(&cluster.kubeconfig_path, &name, &body.namespace, body.replicas) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/kubernetes/clusters/{id}/deployments/{name}/restart?namespace= pub async fn k8s_restart_deployment(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::restart_deployment(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/services?namespace= pub async fn k8s_services(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").filter(|s| !s.is_empty()).map(|s| s.as_str()); HttpResponse::Ok().json(crate::kubernetes::get_services(&cluster.kubeconfig_path, ns)) } /// DELETE /api/kubernetes/clusters/{id}/services/{name}?namespace= pub async fn k8s_delete_service(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::delete_service(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/nodes pub async fn k8s_nodes(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; HttpResponse::Ok().json(crate::kubernetes::get_nodes(&cluster.kubeconfig_path)) } /// GET /api/kubernetes/clusters/{id}/logs/{pod}?namespace=&container=&tail= pub async fn k8s_pod_logs(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, pod) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); let container = query.get("container").map(|s| s.as_str()); let tail: u32 = query.get("tail").and_then(|s| s.parse().ok()).unwrap_or(100); match crate::kubernetes::get_pod_logs(&cluster.kubeconfig_path, &pod, ns, container, tail) { Ok(logs) => HttpResponse::Ok().json(serde_json::json!({ "logs": logs })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/pods/{name}/detail?namespace= pub async fn k8s_pod_detail(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::get_pod_detail(&cluster.kubeconfig_path, &name, ns) { Ok(detail) => HttpResponse::Ok().json(detail), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/pods/{name}/top?namespace= pub async fn k8s_pod_top(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::get_pod_top(&cluster.kubeconfig_path, &name, ns) { Ok(usage) => HttpResponse::Ok().json(usage), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "cpu": "N/A", "memory": "N/A", "error": e })), } } /// POST /api/kubernetes/clusters/{id}/pods/{name}/exec #[derive(Deserialize)] pub struct K8sPodExecRequest { pub namespace: String, #[serde(default)] pub container: Option, pub command: Vec, } pub async fn k8s_pod_exec(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_operator_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; // Security: only allow safe read-only commands let allowed_commands = ["ps", "df", "top", "cat", "ls", "whoami", "hostname", "uname", "env", "printenv", "id", "uptime", "free", "du", "mount", "lsblk", "ip", "ss", "netstat", "date"]; let base_cmd = body.command.first().map(|s| s.as_str()).unwrap_or(""); // Extract just the command name (strip path like /bin/ps -> ps) let cmd_name = base_cmd.rsplit('/').next().unwrap_or(base_cmd); if !allowed_commands.contains(&cmd_name) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": format!("Command '{}' is not allowed. Use the terminal for interactive access.", cmd_name) })); } let cmd_refs: Vec<&str> = body.command.iter().map(|s| s.as_str()).collect(); match crate::kubernetes::exec_in_pod(&cluster.kubeconfig_path, &name, &body.namespace, body.container.as_deref(), &cmd_refs) { Ok(output) => HttpResponse::Ok().json(serde_json::json!({ "output": output })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/pods/{name}/events?namespace= pub async fn k8s_pod_events(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::get_pod_events(&cluster.kubeconfig_path, &name, ns) { Ok(events) => HttpResponse::Ok().json(serde_json::json!({ "events": events })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/storage — full storage overview pub async fn k8s_storage_overview(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").filter(|s| !s.is_empty()).map(|s| s.as_str()); let classes = crate::kubernetes::get_storage_classes(&cluster.kubeconfig_path); let pvs = crate::kubernetes::get_persistent_volumes(&cluster.kubeconfig_path); let pvcs = crate::kubernetes::get_persistent_volume_claims(&cluster.kubeconfig_path, ns); // Include WolfStack storage mounts that are currently mounted (available as backing storage) let wolfstack_mounts: Vec = crate::storage::list_mounts() .iter() .filter(|m| m.status == "mounted") .map(|m| { let type_label = match m.mount_type { crate::storage::MountType::Nfs => "NFS", crate::storage::MountType::Smb => "SMB", crate::storage::MountType::Sshfs => "SSHFS", crate::storage::MountType::Directory => "Directory", crate::storage::MountType::S3 => "S3", crate::storage::MountType::Wolfdisk => "WolfDisk", crate::storage::MountType::Disk => "Disk", }; serde_json::json!({ "id": m.id, "name": m.name, "mount_type": type_label, "source": m.source, "mount_point": m.mount_point, }) }) .collect(); HttpResponse::Ok().json(serde_json::json!({ "storage_classes": classes, "persistent_volumes": pvs, "pvcs": pvcs, "wolfstack_mounts": wolfstack_mounts, })) } /// POST /api/kubernetes/clusters/{id}/storage/pvcs — create a PVC #[derive(Deserialize)] pub struct K8sCreatePvcRequest { pub name: String, pub namespace: String, #[serde(default)] pub storage_class: String, pub size: String, #[serde(default = "default_access_mode")] pub access_mode: String, /// Storage type: "dynamic" (default, uses storage_class), "host_path", "nfs", "wolfstack_mount" #[serde(default = "default_storage_type")] pub storage_type: String, #[serde(default)] pub host_path: Option, #[serde(default)] pub nfs_server: Option, #[serde(default)] pub nfs_path: Option, /// WolfStack mount ID — resolved to its mount_point or NFS source #[serde(default)] pub wolfstack_mount_id: Option, } fn default_access_mode() -> String { "ReadWriteOnce".to_string() } fn default_storage_type() -> String { "dynamic".to_string() } pub async fn k8s_create_pvc(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match body.storage_type.as_str() { "dynamic" | "" => { // Dynamic provisioning via StorageClass (existing behavior) match crate::kubernetes::create_pvc(&cluster.kubeconfig_path, &body.name, &body.namespace, &body.storage_class, &body.size, &body.access_mode) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } "host_path" => { match crate::kubernetes::create_pv_and_pvc(&cluster.kubeconfig_path, crate::kubernetes::PersistentVolumeRequest { name: &body.name, namespace: &body.namespace, size: &body.size, access_mode: &body.access_mode, storage_type: "host_path", host_path: body.host_path.as_deref(), nfs_server: None, nfs_path: None, }) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } "nfs" => { match crate::kubernetes::create_pv_and_pvc(&cluster.kubeconfig_path, crate::kubernetes::PersistentVolumeRequest { name: &body.name, namespace: &body.namespace, size: &body.size, access_mode: &body.access_mode, storage_type: "nfs", host_path: None, nfs_server: body.nfs_server.as_deref(), nfs_path: body.nfs_path.as_deref(), }) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } "wolfstack_mount" => { // Resolve WolfStack mount ID to NFS source or local path let mount_id = match &body.wolfstack_mount_id { Some(id) => id.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "wolfstack_mount_id is required" })), }; let mounts = crate::storage::list_mounts(); let mount = match mounts.iter().find(|m| m.id == mount_id) { Some(m) => m.clone(), None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "WolfStack mount not found" })), }; // NFS mounts → use NFS PV; local/directory mounts → use hostPath PV match mount.mount_type { crate::storage::MountType::Nfs => { // source is "server:/path" let parts: Vec<&str> = mount.source.splitn(2, ':').collect(); if parts.len() != 2 { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid NFS source format" })); } match crate::kubernetes::create_pv_and_pvc(&cluster.kubeconfig_path, crate::kubernetes::PersistentVolumeRequest { name: &body.name, namespace: &body.namespace, size: &body.size, access_mode: &body.access_mode, storage_type: "nfs", host_path: None, nfs_server: Some(parts[0]), nfs_path: Some(parts[1]), }) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } _ => { // Use mount_point as hostPath match crate::kubernetes::create_pv_and_pvc(&cluster.kubeconfig_path, crate::kubernetes::PersistentVolumeRequest { name: &body.name, namespace: &body.namespace, size: &body.size, access_mode: &body.access_mode, storage_type: "host_path", host_path: Some(&mount.mount_point), nfs_server: None, nfs_path: None, }) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } } } other => { HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unknown storage type: {}", other) })) } } } /// DELETE /api/kubernetes/clusters/{id}/storage/pvcs/{name}?namespace= pub async fn k8s_delete_pvc(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::delete_pvc(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/kubernetes/clusters/{id}/deployments/{name}/volumes — add PVC volume mount #[derive(Deserialize)] pub struct K8sAddVolumeRequest { pub namespace: String, pub pvc_name: String, pub mount_path: String, #[serde(default)] pub container: Option, } pub async fn k8s_add_volume(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, dep_name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match crate::kubernetes::add_volume_to_deployment(&cluster.kubeconfig_path, &dep_name, &body.namespace, &body.pvc_name, &body.mount_path, body.container.as_deref()) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/kubernetes/clusters/{id}/deployments/{name}/volumes/{vol_name}?namespace= pub async fn k8s_remove_volume(req: HttpRequest, state: web::Data, path: web::Path<(String, String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, dep_name, vol_name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::remove_volume_from_deployment(&cluster.kubeconfig_path, &dep_name, ns, &vol_name) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/kubernetes/clusters/{id}/apply #[derive(Deserialize)] pub struct K8sApplyRequest { pub yaml: String, #[serde(default)] pub namespace: Option, } /// GET /api/kubernetes/clusters/{id}/resource-yaml?kind=deployment&name=myapp&namespace=default pub async fn k8s_resource_yaml( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let kind = query.get("kind").map(|s| s.as_str()).unwrap_or("pod"); let name = match query.get("name") { Some(n) => n.as_str(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "name parameter required" })), }; let namespace = query.get("namespace").map(|s| s.as_str()).unwrap_or(""); match crate::kubernetes::get_resource_yaml(&cluster.kubeconfig_path, kind, name, namespace) { Ok(yaml) => HttpResponse::Ok().json(serde_json::json!({ "yaml": yaml })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } pub async fn k8s_apply(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; // If namespace specified, prepend it to the yaml or use -n flag via a wrapper let yaml = if let Some(ref ns) = body.namespace { // Add namespace to yaml if not already present if body.yaml.contains("namespace:") { body.yaml.clone() } else { body.yaml.replace("metadata:", &format!("metadata:\n namespace: {}", ns)) } } else { body.yaml.clone() }; match crate::kubernetes::apply_yaml(&cluster.kubeconfig_path, &yaml) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/deployments/{name}/detail?namespace= pub async fn k8s_deployment_detail(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::get_deployment_detail(&cluster.kubeconfig_path, &name, ns) { Ok(detail) => HttpResponse::Ok().json(detail), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// PATCH /api/kubernetes/clusters/{id}/deployments/{name}/image #[derive(Deserialize)] pub struct K8sSetImageRequest { pub namespace: String, pub container: String, pub image: String } pub async fn k8s_set_image(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; match crate::kubernetes::set_deployment_image(&cluster.kubeconfig_path, &name, &body.namespace, &body.container, &body.image) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// PATCH /api/kubernetes/clusters/{id}/deployments/{name}/env #[derive(Deserialize)] pub struct K8sSetEnvRequest { pub namespace: String, pub env: Vec } #[derive(Deserialize)] pub struct K8sEnvVar { pub name: String, pub value: String } pub async fn k8s_set_env(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let env_pairs: Vec<(String, String)> = body.env.iter().map(|e| (e.name.clone(), e.value.clone())).collect(); match crate::kubernetes::set_deployment_env(&cluster.kubeconfig_path, &name, &body.namespace, &env_pairs) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/kubernetes/clusters/{id}/deployments/{name}/full?namespace= — delete deployment + service pub async fn k8s_delete_deployment_full(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, name) = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let ns = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); // Clean up WolfNet route if one exists for this deployment let _ = crate::kubernetes::remove_wolfnet_route(&id, &name, ns); match crate::kubernetes::delete_deployment_and_service(&cluster.kubeconfig_path, &name, ns) { Ok(msg) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// PATCH /api/kubernetes/clusters/{id}/settings — update cluster WolfNet settings #[derive(Deserialize)] pub struct K8sClusterSettingsRequest { #[serde(default)] pub wolfnet_server: Option, #[serde(default)] pub wolfnet_network: Option, #[serde(default)] pub wolfnet_auto_deploy: Option, } pub async fn k8s_cluster_settings(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match crate::kubernetes::update_cluster_settings( &id, body.wolfnet_server.as_deref(), body.wolfnet_network.as_deref(), body.wolfnet_auto_deploy, ) { Ok(cluster) => HttpResponse::Ok().json(serde_json::json!({ "message": "Settings updated", "cluster": cluster })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/kubernetes/clusters/{id}/deploy-app — deploy an app store app to k8s #[derive(Deserialize)] pub struct K8sDeployAppRequest { pub app_id: String, pub container_name: String, #[serde(default = "default_k8s_namespace")] pub namespace: String, #[serde(default = "default_k8s_replicas")] pub replicas: u32, #[serde(default)] pub inputs: std::collections::HashMap, } fn default_k8s_namespace() -> String { "default".to_string() } fn default_k8s_replicas() -> u32 { 1 } pub async fn k8s_deploy_app(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = match crate::kubernetes::get_cluster(&path.into_inner()) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let app = match appstore::get_app(&body.app_id) { Some(a) => a, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": format!("App '{}' not found", body.app_id) })), }; let docker = match app.docker { Some(ref d) => d, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "App does not support Docker/Kubernetes deployment" })), }; if let Some(access) = appstore::docker_host_access(&app.id) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("{} needs host devices ({}) that a Kubernetes pod doesn't get — install it with Docker instead", app.name, access.devices.join(", ")) })); } // Substitute user inputs in env vars let env: Vec = docker.env.iter().map(|e| { let mut val = e.clone(); for (k, v) in &body.inputs { val = val.replace(&format!("${{{}}}", k), v); } val }).collect(); match crate::kubernetes::deploy_app_to_k8s(&cluster.kubeconfig_path, crate::kubernetes::AppDeployment { app_name: &app.name, container_name: &body.container_name, namespace: &body.namespace, image: &docker.image, ports: &docker.ports, env: &env, volumes: &docker.volumes, replicas: body.replicas, }) { Ok(msg) => { // Auto-allocate WolfNet IP if configured and the app exposes ports let mut wolfnet_ip = None; if cluster.wolfnet_auto_deploy && !docker.ports.is_empty() { // Sanitize the container name the same way deploy_app_to_k8s does let svc_name: String = body.container_name .to_lowercase() .chars() .map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' }) .collect::() .trim_matches('-') .to_string(); match crate::kubernetes::allocate_wolfnet_route(&cluster.id, &svc_name, &body.namespace) { Ok(route) => { // Push route to all cluster nodes immediately let wn_status = crate::networking::get_wolfnet_status(); if let Some(ref local_ip) = wn_status.ip { let gateway = local_ip.split('/').next().unwrap_or(local_ip); push_wolfnet_route_to_cluster(&route.wolfnet_ip, gateway, &state).await; } wolfnet_ip = Some(route.wolfnet_ip); }, Err(e) => tracing::warn!("Auto WolfNet route allocation failed: {}", e), } } HttpResponse::Ok().json(serde_json::json!({ "message": msg, "wolfnet_ip": wolfnet_ip })) }, Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/kubernetes/clusters/provision — provision a kubernetes cluster #[derive(Deserialize)] pub struct K8sProvisionRequest { pub name: String, pub server_node_id: String, #[serde(default)] pub agent_node_ids: Vec, #[serde(default = "default_distribution")] pub distribution: String, // "k3s", "microk8s", "kubeadm", "k0s", "rke2" } fn default_distribution() -> String { "k3s".to_string() } /// Run a script locally on this node fn run_script_locally(script: &str) -> Result { let script_path = format!("/tmp/wolfstack-k8s-{}.sh", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()); std::fs::write(&script_path, script).map_err(|e| format!("Failed to write script: {}", e))?; let output = std::process::Command::new("bash").arg(&script_path).output(); let _ = std::fs::remove_file(&script_path); match output { Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).to_string()), Ok(o) => Err(String::from_utf8_lossy(&o.stderr).to_string()), Err(e) => Err(format!("Failed to run script: {}", e)), } } /// Run a script on a remote node via the /api/kubernetes/run-script proxy endpoint async fn run_script_on_remote(address: &str, port: u16, cluster_secret: &str, script: &str) -> Result { let urls = build_node_urls(address, port, "/api/kubernetes/run-script"); let client = &*API_HTTP_CLIENT; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(300)) .peer_auth(cluster_secret) .json(&serde_json::json!({ "script": script })) .send() .await { Ok(resp) if resp.status().is_success() => { let body: serde_json::Value = resp.json().await.unwrap_or_default(); return body["output"].as_str().map(|s| s.to_string()) .ok_or_else(|| body["error"].as_str().unwrap_or("Unknown error").to_string()); } Ok(resp) => { let _ = resp.bytes().await; continue; } Err(_) => continue, } } Err(format!("Failed to reach remote node at {}", address)) } /// Fetch a JSON value from a remote node endpoint async fn fetch_from_remote(address: &str, port: u16, path: &str, cluster_secret: &str) -> Result { let urls = build_node_urls(address, port, path); let client = &*API_HTTP_CLIENT; for url in &urls { match client.get(url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(cluster_secret) .send() .await { Ok(resp) if resp.status().is_success() => { return resp.json().await.map_err(|e| format!("JSON parse error: {}", e)); } Ok(resp) => { let _ = resp.bytes().await; continue; } Err(_) => continue, } } Err(format!("Failed to reach remote node at {}", address)) } pub async fn k8s_provision(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let dist = body.distribution.to_lowercase(); let cluster_type = match dist.as_str() { "k3s" => crate::kubernetes::K8sClusterType::K3s, "microk8s" => crate::kubernetes::K8sClusterType::MicroK8s, "kubeadm" | "k8s" => crate::kubernetes::K8sClusterType::K8s, "k0s" => crate::kubernetes::K8sClusterType::K0s, "rke2" => crate::kubernetes::K8sClusterType::Rke2, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unsupported distribution: {}. Use k3s, microk8s, kubeadm, k0s, or rke2.", dist) })), }; // Find the server node let server_node = match state.cluster.get_node(&body.server_node_id) { Some(n) => n, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Server node not found" })), }; let is_self = server_node.is_self; let server_address = server_node.address.clone(); let server_port = server_node.port; let cluster_name = body.name.clone(); let cluster_secret = state.cluster_secret.clone(); // Generate the server install script based on distribution let script = match dist.as_str() { "k3s" => crate::kubernetes::provision_k3s_server(&server_address, &cluster_name), "microk8s" => crate::kubernetes::provision_microk8s_server(&server_address, &cluster_name), "kubeadm" | "k8s" => crate::kubernetes::provision_kubeadm_server(&server_address, &cluster_name), "k0s" => crate::kubernetes::provision_k0s_server(&server_address, &cluster_name), "rke2" => crate::kubernetes::provision_rke2_server(&server_address, &cluster_name), _ => unreachable!(), }; let script = match script { Ok(s) => s, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; // 1. Install server let server_result = if is_self { run_script_locally(&script) } else { run_script_on_remote(&server_address, server_port, &cluster_secret, &script).await }; if let Err(e) = server_result { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{} server install failed: {}", dist, e) })); } // 2. Get the kubeconfig path let default_kubeconfig_path = match dist.as_str() { "k3s" => "/etc/rancher/k3s/k3s.yaml", "microk8s" => "/var/snap/microk8s/current/credentials/client.config", "kubeadm" | "k8s" => "/etc/kubernetes/admin.conf", "k0s" => "/etc/k0s/kubeconfig", "rke2" => "/etc/rancher/rke2/rke2.yaml", _ => "/root/.kube/config", }; let api_port: u16 = match dist.as_str() { "microk8s" => 16443, "rke2" => 9345, _ => 6443, }; let api_url = format!("https://{}:{}", crate::netaddr::bracket_host(&server_address), api_port); let cluster_id = format!("k8s-{}", cluster_name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-")); let kubeconfig_path = default_kubeconfig_path.to_string(); // Register the cluster on the SERVER node (not the UI node) // This ensures kubernetes.json, kubeconfig, WolfNet routes, and DNAT all live // on the node that actually runs the K8s cluster. let cluster = if is_self { match crate::kubernetes::add_cluster(cluster_id.clone(), cluster_name.clone(), kubeconfig_path.clone(), api_url.clone(), cluster_type) { Ok(c) => c, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } else { // Register on the remote server node via its /api/kubernetes/clusters endpoint let import_body = serde_json::json!({ "name": cluster_name, "kubeconfig_path": kubeconfig_path, "cluster_type": dist, }); let urls = build_node_urls(&server_address, server_port, "/api/kubernetes/clusters"); let client = &*API_HTTP_CLIENT; let mut registered = false; let mut cluster_resp = None; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&cluster_secret) .json(&import_body) .send() .await { Ok(resp) if resp.status().is_success() => { cluster_resp = resp.json::().await.ok(); registered = true; break; } Ok(resp) => { let _ = resp.bytes().await; continue; } Err(_) => continue, } } if !registered { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{} installed but failed to register cluster on server node {}", dist, server_address) })); } // Return the cluster object from the remote registration match cluster_resp.and_then(|v| serde_json::from_value::(v["cluster"].clone()).ok()) { Some(c) => c, None => { // Construct a minimal cluster object for the response crate::kubernetes::K8sCluster { id: cluster_id.clone(), name: cluster_name.clone(), kubeconfig_path: kubeconfig_path.clone(), api_url: api_url.clone(), cluster_type, created_at: chrono::Utc::now().to_rfc3339(), nodes: Vec::new(), wolfnet_server: String::new(), wolfnet_network: String::new(), wolfnet_auto_deploy: true, wolfnet_routes: Vec::new(), owner_node_id: String::new(), } } } }; // 3. Install agents on worker nodes let mut agent_errors = Vec::new(); if !body.agent_node_ids.is_empty() { // Get join credentials from the server let join_info: Result = if is_self { match dist.as_str() { "k3s" => crate::kubernetes::get_k3s_token(&kubeconfig_path), "microk8s" => crate::kubernetes::get_microk8s_join_command(), "kubeadm" | "k8s" => crate::kubernetes::get_kubeadm_join_command(), "k0s" => crate::kubernetes::get_k0s_join_token(), "rke2" => crate::kubernetes::get_rke2_join_token(), _ => Err("Unsupported distribution".to_string()), } } else { // Get join info from remote server fetch_from_remote(&server_address, server_port, "/api/kubernetes/join-token", &cluster_secret).await .and_then(|body| body["token"].as_str().map(|s| s.to_string()) .ok_or_else(|| "No join token in response".to_string())) }; let join_info = match join_info { Ok(t) => t, Err(e) => { return HttpResponse::Ok().json(serde_json::json!({ "message": format!("{} server provisioned but failed to get join credentials for agents: {}", dist, e), "cluster": cluster, })); } }; for agent_node_id in &body.agent_node_ids { let agent_node = match state.cluster.get_node(agent_node_id) { Some(n) => n, None => { agent_errors.push(format!("{}: node not found", agent_node_id)); continue; } }; let agent_script = match dist.as_str() { "k3s" => crate::kubernetes::provision_k3s_agent(&agent_node.address, &api_url, &join_info), "microk8s" => crate::kubernetes::provision_microk8s_agent(&join_info), "kubeadm" | "k8s" => crate::kubernetes::provision_kubeadm_agent(&join_info), "k0s" => crate::kubernetes::provision_k0s_agent(&join_info), "rke2" => crate::kubernetes::provision_rke2_agent(&api_url, &join_info), _ => Err("Unsupported distribution".to_string()), }; let agent_script = match agent_script { Ok(s) => s, Err(e) => { agent_errors.push(format!("{}: {}", agent_node.hostname, e)); continue; } }; let result = if agent_node.is_self { run_script_locally(&agent_script) } else { run_script_on_remote(&agent_node.address, agent_node.port, &cluster_secret, &agent_script).await }; if let Err(e) = result { agent_errors.push(format!("{}: {}", agent_node.hostname, e)); } } } let mut msg = format!("{} cluster '{}' provisioned successfully", dist, cluster_name); if !agent_errors.is_empty() { msg.push_str(&format!(". Agent errors: {}", agent_errors.join("; "))); } HttpResponse::Ok().json(serde_json::json!({ "message": msg, "cluster": cluster })) } /// POST /api/kubernetes/prepare-provision — generate provisioning scripts for live terminal execution /// Returns session IDs that can be used with the k8s-provision console type. pub async fn k8s_prepare_provision(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let dist = body.distribution.to_lowercase(); if !["k3s", "microk8s", "kubeadm", "k8s", "k0s", "rke2"].contains(&dist.as_str()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Unsupported distribution: {}. Use k3s, microk8s, kubeadm, k0s, or rke2.", dist) })); } let server_node = match state.cluster.get_node(&body.server_node_id) { Some(n) => n, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Server node not found" })), }; let server_address = server_node.address.clone(); let server_port = server_node.port; let cluster_name = body.name.clone(); let cluster_secret = state.cluster_secret.clone(); let ts = chrono::Utc::now().timestamp_millis(); // --- Generate server install script --- let cluster_type = match dist.as_str() { "k3s" => crate::kubernetes::K8sClusterType::K3s, "microk8s" => crate::kubernetes::K8sClusterType::MicroK8s, "k0s" => crate::kubernetes::K8sClusterType::K0s, "rke2" => crate::kubernetes::K8sClusterType::Rke2, _ => crate::kubernetes::K8sClusterType::K8s, }; let server_install = match dist.as_str() { "k3s" => crate::kubernetes::provision_k3s_server(&server_address, &cluster_name), "microk8s" => crate::kubernetes::provision_microk8s_server(&server_address, &cluster_name), "kubeadm" | "k8s" => crate::kubernetes::provision_kubeadm_server(&server_address, &cluster_name), "k0s" => crate::kubernetes::provision_k0s_server(&server_address, &cluster_name), "rke2" => crate::kubernetes::provision_rke2_server(&server_address, &cluster_name), _ => unreachable!(), }; let server_install = match server_install { Ok(s) => s, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; // Wrap in a nicer script with banner let server_session_id = format!("{}-server-{}", dist, ts); let kubeconfig_path = match dist.as_str() { "k3s" => "/etc/rancher/k3s/k3s.yaml", "microk8s" => "/var/snap/microk8s/current/credentials/client.config", "k0s" => "/etc/k0s/kubeconfig", "rke2" => "/etc/rancher/rke2/rke2.yaml", _ => "/etc/kubernetes/admin.conf", }; let api_port: u16 = match dist.as_str() { "microk8s" => 16443, "rke2" => 9345, _ => 6443, }; let server_script = format!( "#!/bin/bash\nset -e\n\n\ printf '\\033[1;36m━━━ WolfKube — Installing {dist} server on {addr} ━━━\\033[0m\\n'\n\ printf '\\033[0;90mCluster: {name}\\033[0m\\n'\n\ echo ''\n\n\ {install}\n\n\ echo ''\n\ printf '\\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\033[0m\\n'\n\ printf '\\033[1;32m {dist} server installed successfully!\\033[0m\\n'\n\ printf '\\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\033[0m\\n'\n\ printf '\\033[0;36m Kubeconfig: {kubeconfig}\\033[0m\\n'\n", dist = dist, addr = server_address, name = cluster_name, install = server_install, kubeconfig = kubeconfig_path, ); let server_script_path = format!("/tmp/wolfstack-k8s-provision-{}.sh", server_session_id); // Write script: locally or on remote node let mut sessions = Vec::new(); if server_node.is_self { if let Err(e) = std::fs::write(&server_script_path, &server_script) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write script: {}", e) })); } let _ = std::process::Command::new("chmod").args(["+x", &server_script_path]).output(); } else { // Write script on remote node via API let write_result = run_script_on_remote( &server_address, server_port, &cluster_secret, &format!("cat > {} << 'WOLFKUBE_SCRIPT_EOF'\n{}\nWOLFKUBE_SCRIPT_EOF\nchmod +x {}", server_script_path, server_script, server_script_path), ).await; if let Err(e) = write_result { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write script on remote node: {}", e) })); } } sessions.push(serde_json::json!({ "session_id": server_session_id, "node_id": body.server_node_id, "hostname": server_node.hostname, "role": "server", "is_remote": !server_node.is_self, })); HttpResponse::Ok().json(serde_json::json!({ "sessions": sessions, "cluster_name": cluster_name, "distribution": dist, "cluster_type": cluster_type.to_string(), "kubeconfig_path": kubeconfig_path, "api_url": format!("https://{}:{}", crate::netaddr::bracket_host(&server_address), api_port), "server_address": server_address, "server_node_id": body.server_node_id, "agent_node_ids": body.agent_node_ids, })) } /// POST /api/kubernetes/prepare-provision-agents — generate agent scripts after server is ready #[derive(Deserialize)] #[allow(dead_code)] pub struct K8sPrepareAgentsRequest { pub distribution: String, pub cluster_name: String, pub kubeconfig_path: String, pub api_url: String, pub server_address: String, #[serde(default)] pub server_node_id: String, pub agent_node_ids: Vec, } pub async fn k8s_prepare_provision_agents(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let dist = body.distribution.to_lowercase(); let cluster_secret = state.cluster_secret.clone(); let ts = chrono::Utc::now().timestamp_millis(); // Determine if the server node is remote let server_is_self = if body.server_node_id.is_empty() { true // fallback: assume local } else { state.cluster.get_node(&body.server_node_id).map(|n| n.is_self).unwrap_or(true) }; let server_address = body.server_address.clone(); let server_port = if !body.server_node_id.is_empty() { state.cluster.get_node(&body.server_node_id).map(|n| n.port).unwrap_or(8553) } else { 8553 }; // Get join token/command — from local node or remote server let join_info: Result = if server_is_self { match dist.as_str() { "k3s" => crate::kubernetes::get_k3s_token(&body.kubeconfig_path), "microk8s" => crate::kubernetes::get_microk8s_join_command(), "kubeadm" | "k8s" => crate::kubernetes::get_kubeadm_join_command(), "k0s" => crate::kubernetes::get_k0s_join_token(), "rke2" => crate::kubernetes::get_rke2_join_token(), _ => Err("Unsupported distribution".to_string()), } } else { // Fetch join token from the remote server node fetch_from_remote(&server_address, server_port, "/api/kubernetes/join-token", &cluster_secret).await .and_then(|body| body["token"].as_str().map(|s| s.to_string()) .ok_or_else(|| "No join token in response".to_string())) }; let join_info = match join_info { Ok(t) => t, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to get join credentials: {}", e) })), }; let mut sessions = Vec::new(); let mut errors = Vec::new(); for (i, agent_node_id) in body.agent_node_ids.iter().enumerate() { let agent_node = match state.cluster.get_node(agent_node_id) { Some(n) => n, None => { errors.push(format!("{}: node not found", agent_node_id)); continue; } }; let agent_install = match dist.as_str() { "k3s" => crate::kubernetes::provision_k3s_agent(&agent_node.address, &body.api_url, &join_info), "microk8s" => crate::kubernetes::provision_microk8s_agent(&join_info), "kubeadm" | "k8s" => crate::kubernetes::provision_kubeadm_agent(&join_info), "k0s" => crate::kubernetes::provision_k0s_agent(&join_info), "rke2" => crate::kubernetes::provision_rke2_agent(&body.api_url, &join_info), _ => Err("Unsupported".to_string()), }; let agent_install = match agent_install { Ok(s) => s, Err(e) => { errors.push(format!("{}: {}", agent_node.hostname, e)); continue; } }; let session_id = format!("{}-agent{}-{}", dist, i, ts); let script = format!( "#!/bin/bash\nset -e\n\n\ printf '\\033[1;36m━━━ WolfKube — Joining {hostname} as {dist} worker ━━━\\033[0m\\n'\n\ echo ''\n\n\ {install}\n\n\ echo ''\n\ printf '\\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\033[0m\\n'\n\ printf '\\033[1;32m {hostname} joined the cluster!\\033[0m\\n'\n\ printf '\\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\033[0m\\n'\n", hostname = agent_node.hostname, dist = dist, install = agent_install, ); let script_path = format!("/tmp/wolfstack-k8s-provision-{}.sh", session_id); if agent_node.is_self { if let Err(e) = std::fs::write(&script_path, &script) { errors.push(format!("{}: {}", agent_node.hostname, e)); continue; } let _ = std::process::Command::new("chmod").args(["+x", &script_path]).output(); } else { let write_result = run_script_on_remote( &agent_node.address, agent_node.port, &cluster_secret, &format!("cat > {} << 'WOLFKUBE_SCRIPT_EOF'\n{}\nWOLFKUBE_SCRIPT_EOF\nchmod +x {}", script_path, script, script_path), ).await; if let Err(e) = write_result { errors.push(format!("{}: {}", agent_node.hostname, e)); continue; } } sessions.push(serde_json::json!({ "session_id": session_id, "node_id": agent_node_id, "hostname": agent_node.hostname, "role": "agent", "is_remote": !agent_node.is_self, })); } HttpResponse::Ok().json(serde_json::json!({ "sessions": sessions, "errors": errors, })) } /// POST /api/kubernetes/run-script — run a provisioning script on this node (cluster-secret auth) #[derive(Deserialize)] pub struct K8sRunScriptRequest { pub script: String, } pub async fn k8s_run_script(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Agent-style auth: cluster secret header // require_auth already accepts a valid X-WolfStack-Secret (via // auth::validate_inter_node_secret, which also covers the on-disk // secret and compares in constant time), so the previous inline // `!= state.cluster_secret` pre-check was redundant AND leaked // timing on the secret. Behaviour is unchanged; the leak is gone. if let Err(resp) = require_auth(&req, &state) { return resp; } let script_path = format!("/tmp/wolfstack-k8s-provision-{}.sh", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()); if let Err(e) = std::fs::write(&script_path, &body.script) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write script: {}", e) })); } let output = std::process::Command::new("bash").arg(&script_path).output(); let _ = std::fs::remove_file(&script_path); match output { Ok(o) if o.status.success() => { HttpResponse::Ok().json(serde_json::json!({ "output": String::from_utf8_lossy(&o.stdout).to_string() })) } Ok(o) => { HttpResponse::InternalServerError().json(serde_json::json!({ "error": String::from_utf8_lossy(&o.stderr).to_string() })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to run script: {}", e) })), } } /// GET /api/kubernetes/kubeconfig — return the local kubeconfig (cluster-secret auth) /// Tries k3s, microk8s, kubeadm in order of detection pub async fn k8s_kubeconfig(req: HttpRequest, state: web::Data) -> HttpResponse { // require_auth already accepts a valid X-WolfStack-Secret (via // auth::validate_inter_node_secret, which also covers the on-disk // secret and compares in constant time), so the previous inline // `!= state.cluster_secret` pre-check was redundant AND leaked // timing on the secret. Behaviour is unchanged; the leak is gone. if let Err(resp) = require_auth(&req, &state) { return resp; } // Try known kubeconfig paths in order let paths = [ "/etc/rancher/k3s/k3s.yaml", "/var/snap/microk8s/current/credentials/client.config", "/etc/kubernetes/admin.conf", "/etc/k0s/kubeconfig", "/etc/rancher/rke2/rke2.yaml", "/root/.kube/config", ]; for path in &paths { if let Ok(content) = std::fs::read_to_string(path) { return HttpResponse::Ok().json(serde_json::json!({ "kubeconfig": content, "path": path })); } } HttpResponse::NotFound().json(serde_json::json!({ "error": "No kubeconfig found on this node" })) } /// GET /api/kubernetes/join-token — return the join token/command for this node (cluster-secret auth) pub async fn k8s_join_token(req: HttpRequest, state: web::Data) -> HttpResponse { // require_auth already accepts a valid X-WolfStack-Secret (via // auth::validate_inter_node_secret, which also covers the on-disk // secret and compares in constant time), so the previous inline // `!= state.cluster_secret` pre-check was redundant AND leaked // timing on the secret. Behaviour is unchanged; the leak is gone. if let Err(resp) = require_auth(&req, &state) { return resp; } // Try k3s token if std::path::Path::new("/var/lib/rancher/k3s/server/node-token").exists() && let Ok(token) = crate::kubernetes::get_k3s_token("/etc/rancher/k3s/k3s.yaml") { return HttpResponse::Ok().json(serde_json::json!({ "token": token, "type": "k3s" })) } // Try microk8s join if let Ok(join) = crate::kubernetes::get_microk8s_join_command() { return HttpResponse::Ok().json(serde_json::json!({ "token": join, "type": "microk8s" })); } // Try kubeadm join if let Ok(join) = crate::kubernetes::get_kubeadm_join_command() { return HttpResponse::Ok().json(serde_json::json!({ "token": join, "type": "kubeadm" })); } // Try k0s join if let Ok(token) = crate::kubernetes::get_k0s_join_token() { return HttpResponse::Ok().json(serde_json::json!({ "token": token, "type": "k0s" })); } // Try RKE2 join if let Ok(token) = crate::kubernetes::get_rke2_join_token() { return HttpResponse::Ok().json(serde_json::json!({ "token": token, "type": "rke2" })); } HttpResponse::NotFound().json(serde_json::json!({ "error": "No join token available on this node" })) } /// POST /api/kubernetes/uninstall — prepare an uninstall script and return a session for terminal #[derive(Deserialize)] pub struct K8sUninstallRequest { pub cluster_type: String, } pub async fn k8s_uninstall(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Accept either session auth or cluster-secret auth (for proxied calls) // require_auth already accepts a valid X-WolfStack-Secret (via // auth::validate_inter_node_secret, which also covers the on-disk // secret and compares in constant time), so the previous inline // `!= state.cluster_secret` pre-check was redundant AND leaked // timing on the secret. Behaviour is unchanged; the leak is gone. if let Err(resp) = require_auth(&req, &state) { return resp; } let script = match crate::kubernetes::uninstall_script(&body.cluster_type) { Ok(s) => s, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), }; let ts = chrono::Utc::now().timestamp_millis(); let session_id = format!("{}-uninstall-{}", body.cluster_type, ts); let full_script = format!( "#!/bin/bash\n\ printf '\\033[1;31m━━━ WolfKube — Uninstalling {} ━━━\\033[0m\\n'\n\ echo ''\n\ {}\n\ echo ''\n\ printf '\\033[1;32m━━━ Uninstall complete ━━━\\033[0m\\n'\n", body.cluster_type, script ); let script_path = format!("/tmp/wolfstack-k8s-provision-{}.sh", session_id); if let Err(e) = std::fs::write(&script_path, &full_script) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write uninstall script: {}", e) })); } let _ = std::process::Command::new("chmod").args(["+x", &script_path]).output(); HttpResponse::Ok().json(serde_json::json!({ "session_id": session_id, })) } /// Push a WolfNet route to all other WolfStack nodes in the cluster. /// This ensures K8s WolfNet IPs are immediately reachable from all nodes /// without waiting for the next polling cycle. async fn push_wolfnet_route_to_cluster(wolfnet_ip: &str, gateway_ip: &str, state: &web::Data) { let nodes = state.cluster.get_all_nodes(); let secret = state.cluster_secret.clone(); let route_body = serde_json::json!({ "routes": { wolfnet_ip: gateway_ip } }); for node in &nodes { if node.is_self || node.node_type != "wolfstack" { continue; } let urls = build_node_urls(&node.address, node.port, "/api/agent/wolfnet-routes"); let secret = secret.clone(); let body = route_body.clone(); tokio::spawn(async move { let client = &*API_HTTP_CLIENT; for url in &urls { if let Ok(resp) = client.post(url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .json(&body) .send() .await { let success = resp.status().is_success(); let _ = resp.bytes().await; if success { break; } } } }); } } /// POST /api/kubernetes/clusters/{id}/wolfnet — allocate a WolfNet IP route for a deployment #[derive(Deserialize)] pub struct K8sWolfNetRouteRequest { pub deployment_name: String, #[serde(default = "default_k8s_namespace")] pub namespace: String, } pub async fn k8s_deploy_wolfnet(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match crate::kubernetes::allocate_wolfnet_route(&id, &body.deployment_name, &body.namespace) { Ok(route) => { // Push route to all cluster nodes immediately let wn_status = crate::networking::get_wolfnet_status(); if let Some(ref local_ip) = wn_status.ip { let gateway = local_ip.split('/').next().unwrap_or(local_ip); push_wolfnet_route_to_cluster(&route.wolfnet_ip, gateway, &state).await; } HttpResponse::Ok().json(serde_json::json!({ "message": format!("Allocated WolfNet IP {} for {}", route.wolfnet_ip, route.deployment_name), "route": route, })) }, Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/kubernetes/clusters/{id}/wolfnet — remove a WolfNet route for a deployment pub async fn k8s_remove_wolfnet(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let deployment_name = match query.get("deployment") { Some(n) => n.as_str(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Missing 'deployment' query parameter" })), }; let namespace = query.get("namespace").map(|s| s.as_str()).unwrap_or("default"); match crate::kubernetes::remove_wolfnet_route(&id, deployment_name, namespace) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "message": format!("WolfNet route removed for {}", deployment_name) })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/kubernetes/clusters/{id}/wolfnet — WolfNet status for k8s cluster nodes + deployment routes pub async fn k8s_wolfnet_status(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let cluster = match crate::kubernetes::get_cluster(&id) { Some(c) => c, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Cluster not found" })), }; let mut status = crate::kubernetes::get_wolfnet_node_status(&cluster.kubeconfig_path); status["routes"] = serde_json::json!(cluster.wolfnet_routes); status["wolfnet_auto_deploy"] = serde_json::json!(cluster.wolfnet_auto_deploy); HttpResponse::Ok().json(status) } // ─── Security (Fail2ban, iptables, UFW) ─── /// Helper: check if a command exists on the system fn command_exists(cmd: &str) -> bool { std::process::Command::new("which").arg(cmd) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status().map(|s| s.success()).unwrap_or(false) } /// Helper: run a shell command, return stdout fn run_shell(cmd: &str) -> Result { let output = std::process::Command::new("bash") .arg("-c") .arg(cmd) .output() .map_err(|e| format!("Failed to execute: {}", e))?; if output.status.success() { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } else { let stderr = String::from_utf8_lossy(&output.stderr).to_string(); Err(if stderr.is_empty() { "Command failed".into() } else { stderr }) } } /// GET /api/security/status — get fail2ban, iptables, and ufw status pub async fn security_status( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } // Fail2ban let f2b_installed = command_exists("fail2ban-client"); let f2b_status = if f2b_installed { match run_shell("fail2ban-client status 2>/dev/null") { Ok(out) => Some(out), Err(_) => Some("installed but not running".to_string()), } } else { None }; let f2b_banned = if f2b_installed { // `fail2ban-client status sshd` prints every currently-banned IP // space-separated on ONE line — "`- Banned IP list:\t1.2.3.4 5.6.7.8" // (beautifier.py renders list values with `" ".join(...)`). Strip the // label and emit one IP per line for the UI; an empty ban list yields // an empty string. The raw grep'd line used to leak through here, so // zero bans rendered as "Banned (1)" with the label itself shown as // the banned "IP" (RutgerDiehard, 2026-07-02). run_shell("fail2ban-client status sshd 2>/dev/null | sed -n 's/.*Banned IP list:[[:space:]]*//p' | tr -s ' \\t' '\\n' | sed '/^$/d'") .unwrap_or_default() } else { String::new() }; let f2b_jails = if f2b_installed { run_shell("fail2ban-client status 2>/dev/null | grep 'Jail list' | sed 's/.*Jail list:\\s*//' | tr -d '\\t'") .unwrap_or_default().trim().to_string() } else { String::new() }; // jail.local config let jail_local_exists = std::path::Path::new("/etc/fail2ban/jail.local").exists(); let jail_local_content = if jail_local_exists { std::fs::read_to_string("/etc/fail2ban/jail.local").unwrap_or_default() } else { String::new() }; // Parse key settings from jail.local let parse_val = |content: &str, key: &str| -> String { content.lines() .filter(|l| !l.trim_start().starts_with('#')) .find(|l| l.trim().starts_with(key)) .and_then(|l| l.split('=').nth(1)) .map(|v| v.trim().to_string()) .unwrap_or_default() }; let bantime = parse_val(&jail_local_content, "bantime"); let findtime = parse_val(&jail_local_content, "findtime"); let maxretry = parse_val(&jail_local_content, "maxretry"); let ignoreip = parse_val(&jail_local_content, "ignoreip"); // iptables — always available let iptables_rules = run_shell("iptables -L -n --line-numbers 2>/dev/null || echo 'iptables not available'") .unwrap_or_else(|e| e); // UFW let ufw_installed = command_exists("ufw"); let ufw_status = if ufw_installed { run_shell("ufw status verbose 2>/dev/null").unwrap_or_else(|e| e) } else { String::new() }; // System updates — detect package manager and count pending updates let (pkg_manager, updates_count, updates_list) = if command_exists("apt") { let list = run_shell("apt list --upgradable 2>/dev/null | grep -v '^Listing'") .unwrap_or_default(); let count = list.lines().filter(|l| !l.trim().is_empty()).count(); ("apt", count, list.trim().to_string()) } else if command_exists("dnf") { let list = run_shell("dnf check-update --quiet 2>/dev/null") .unwrap_or_default(); let count = list.lines().filter(|l| !l.trim().is_empty()).count(); ("dnf", count, list.trim().to_string()) } else if command_exists("yum") { let list = run_shell("yum check-update --quiet 2>/dev/null") .unwrap_or_default(); let count = list.lines().filter(|l| !l.trim().is_empty()).count(); ("yum", count, list.trim().to_string()) } else if command_exists("pacman") { let list = run_shell("pacman -Qu 2>/dev/null") .unwrap_or_default(); let count = list.lines().filter(|l| !l.trim().is_empty()).count(); ("pacman", count, list.trim().to_string()) } else { ("unknown", 0, String::new()) }; HttpResponse::Ok().json(serde_json::json!({ "fail2ban": { "installed": f2b_installed, "status": f2b_status, "banned": f2b_banned, "jails": f2b_jails, "jail_local_exists": jail_local_exists, "bantime": bantime, "findtime": findtime, "maxretry": maxretry, "ignoreip": ignoreip, }, "iptables": { "rules": iptables_rules, }, "ufw": { "installed": ufw_installed, "status": ufw_status, }, "updates": { "package_manager": pkg_manager, "count": updates_count, "list": updates_list, } })) } /// Generate a distro-appropriate jail.local configuration fn generate_jail_local(cluster_ips: &[String]) -> String { // ── Detect distro from /etc/os-release ── let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default(); let get_field = |key: &str| -> String { for line in os_release.lines() { if line.starts_with(key) { return line.split_once('=').map(|x| x.1).unwrap_or("").trim_matches('"').to_string(); } } String::new() }; let distro_id = get_field("ID=").to_lowercase(); let version_id = get_field("VERSION_ID="); let version_num: f32 = version_id.parse().unwrap_or(0.0); // ── Determine backend ── // Debian 12+, Ubuntu 22.04+, and most modern systemd distros don't ship rsyslog // and need backend = systemd to read from journald let use_systemd_backend = match distro_id.as_str() { "debian" => version_num >= 12.0, "ubuntu" => version_num >= 22.04, _ => { // Check if rsyslog is installed; if not, use systemd !std::path::Path::new("/var/log/auth.log").exists() || std::path::Path::new("/run/systemd/system").exists() } }; // ── Determine banaction ── // Debian 13+ defaults to nftables; also check if nft binary exists let use_nftables = match distro_id.as_str() { "debian" => version_num >= 13.0, _ => false, } || command_exists("nft"); let backend = if use_systemd_backend { "systemd" } else { "auto" }; let banaction = if use_nftables { "nftables-multiport" } else { "iptables-multiport" }; // Auto-whitelist WolfStack cluster nodes so fail2ban never bans a peer // (SSH/journald noise between nodes would otherwise trip the sshd jail and // break cluster connectivity — klasSponsor 2026-06-08). Loopback always // first, then valid cluster IPs (skip loopback/unspecified). let mut ignore_entries: Vec = vec!["127.0.0.1/8".to_string(), "::1".to_string()]; for ip in cluster_ips { if let Ok(parsed) = ip.parse::() && !parsed.is_loopback() && !parsed.is_unspecified() && !ignore_entries.iter().any(|e| e == ip) { ignore_entries.push(ip.clone()); } } // Also whitelist the host's own container/workload bridges (Docker/LXC/ // libvirt) so fail2ban never bans a local container that hit the sshd jail // (klasSponsor 2026-06-08). These are valid CIDR ignoreip entries. for cidr in crate::networking::collect_workload_subnets() { if !ignore_entries.iter().any(|e| e == &cidr) { ignore_entries.push(cidr); } } let ignoreip = ignore_entries.join(" "); let mut config = format!( "# Generated by WolfStack for {distro} {version}\n\ # Last generated: {timestamp}\n\n\ [DEFAULT]\n\ bantime = 1h\n\ findtime = 10m\n\ maxretry = 5\n\ ignoreip = {ignoreip}\n\ backend = {backend}\n\ banaction = {banaction}\n\n\ [sshd]\n\ enabled = true\n\ port = ssh\n\ filter = sshd\n\ maxretry = 3\n", distro = if distro_id.is_empty() { "unknown".to_string() } else { distro_id.clone() }, version = version_id, timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), backend = backend, banaction = banaction, ); // Only set logpath for file-based backends (not systemd) if !use_systemd_backend { config.push_str("logpath = /var/log/auth.log\n"); } config } /// POST /api/security/fail2ban/install — install fail2ban + create default jail.local pub async fn security_fail2ban_install( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } // Install fail2ban + python3-systemd (needed for systemd backend) if run_shell("apt-get update && apt-get install -y fail2ban python3-systemd").is_err() { // Try without python3-systemd (may not exist on all distros) if let Err(e) = run_shell("apt-get install -y fail2ban") { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } } // Create default jail.local if it doesn't exist if !std::path::Path::new("/etc/fail2ban/jail.local").exists() { let config = generate_jail_local(&state.cluster.wolfstack_node_ips()); let _ = std::fs::write("/etc/fail2ban/jail.local", config); } match run_shell("systemctl enable --now fail2ban && systemctl restart fail2ban") { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/security/fail2ban/rebuild — regenerate jail.local with distro-appropriate settings pub async fn security_fail2ban_rebuild( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } // Ensure python3-systemd is present let _ = run_shell("apt-get install -y python3-systemd 2>/dev/null"); let config = generate_jail_local(&state.cluster.wolfstack_node_ips()); if let Err(e) = std::fs::write("/etc/fail2ban/jail.local", &config) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write jail.local: {}", e) })); } match run_shell("systemctl restart fail2ban") { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out, "config": config, "message": "jail.local regenerated with distro-appropriate settings" })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "warning": format!("Config written but restart failed: {}", e), "config": config })), } } /// GET /api/security/protected-block-events — recent refused attempts to /// kernel-block a WolfStack cluster-node IP. Drives the red banner that warns /// the operator a node tried to ban a peer (klasSponsor 2026-06-08). Also /// returns the current count of auto-whitelisted cluster IPs for context. pub async fn security_protected_block_events(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let events = crate::auth::recent_protected_block_events(); HttpResponse::Ok().json(serde_json::json!({ "events": events, "protected_count": state.cluster.wolfstack_node_ips().len(), })) } /// Parse jail config file into sections and their key-value pairs fn parse_jail_config(content: &str) -> serde_json::Map { let mut sections = serde_json::Map::new(); let mut current_section = String::new(); let mut current_settings = serde_json::Map::new(); for line in content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { continue; } if trimmed.starts_with('[') && trimmed.ends_with(']') { // Save previous section if it exists if !current_section.is_empty() && !current_settings.is_empty() { sections.insert(current_section.clone(), serde_json::Value::Object(current_settings.clone())); } current_section = trimmed[1..trimmed.len()-1].to_string(); current_settings = serde_json::Map::new(); } else if let Some(eq_pos) = trimmed.find('=') { let key = trimmed[..eq_pos].trim().to_string(); let value = trimmed[eq_pos+1..].trim().to_string(); current_settings.insert(key, serde_json::Value::String(value)); } } // Save last section if !current_section.is_empty() && !current_settings.is_empty() { sections.insert(current_section, serde_json::Value::Object(current_settings)); } sections } /// GET /api/security/fail2ban/config — read jail.local with parsed sections pub async fn security_fail2ban_config_get( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } // Read local config let local_exists = std::path::Path::new("/etc/fail2ban/jail.local").exists(); let local_content = if local_exists { std::fs::read_to_string("/etc/fail2ban/jail.local").unwrap_or_default() } else { String::new() }; let local_sections = parse_jail_config(&local_content); // Read default config for available jails let default_content = std::fs::read_to_string("/etc/fail2ban/jail.conf").unwrap_or_default(); let default_sections = parse_jail_config(&default_content); HttpResponse::Ok().json(serde_json::json!({ "exists": local_exists, "content": local_content, "local_sections": local_sections, "default_sections": default_sections, })) } /// POST /api/security/fail2ban/section — save a single jail section pub async fn security_fail2ban_section_save( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let section_name = body.get("section").and_then(|v| v.as_str()).unwrap_or(""); let settings = body.get("settings").and_then(|v| v.as_object()); if section_name.is_empty() || settings.is_none() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Section name and settings required" })); } // Read existing jail.local let content = std::fs::read_to_string("/etc/fail2ban/jail.local").unwrap_or_default(); // Parse into sections let mut current_section = String::new(); let mut section_lines: std::collections::HashMap> = std::collections::HashMap::new(); let mut section_order = Vec::new(); for line in content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { if !current_section.is_empty() { section_lines.entry(current_section.clone()).or_default().push(line.to_string()); } continue; } if trimmed.starts_with('[') && trimmed.ends_with(']') { current_section = trimmed[1..trimmed.len()-1].to_string(); if !section_order.contains(¤t_section) { section_order.push(current_section.clone()); } section_lines.entry(current_section.clone()).or_default().push(line.to_string()); } else if !current_section.is_empty() { section_lines.entry(current_section.clone()).or_default().push(line.to_string()); } } // Update or create section if !section_order.contains(§ion_name.to_string()) { section_order.push(section_name.to_string()); } let settings_map = settings.unwrap(); let mut new_lines = vec![format!("[{}]", section_name)]; for (key, val) in settings_map.iter() { if let Some(s) = val.as_str() { new_lines.push(format!("{} = {}", key, s)); } } section_lines.insert(section_name.to_string(), new_lines); // Reconstruct config let mut new_content = String::new(); for section in §ion_order { if let Some(lines) = section_lines.get(section) { for line in lines { new_content.push_str(line); new_content.push('\n'); } new_content.push('\n'); } } if let Err(e) = std::fs::write("/etc/fail2ban/jail.local", &new_content) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write: {}", e) })); } match run_shell("systemctl restart fail2ban") { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "warning": format!("Saved but restart failed: {}", e) })), } } /// POST /api/security/fail2ban/section/delete — delete a jail section pub async fn security_fail2ban_section_delete( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let section_name = body.get("section").and_then(|v| v.as_str()).unwrap_or(""); if section_name.is_empty() || section_name == "DEFAULT" { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Cannot delete DEFAULT section" })); } let content = std::fs::read_to_string("/etc/fail2ban/jail.local").unwrap_or_default(); let mut new_content = String::new(); let mut skip = false; for line in content.lines() { let trimmed = line.trim(); if trimmed.starts_with('[') && trimmed.ends_with(']') { let current = &trimmed[1..trimmed.len()-1]; skip = current == section_name; if !skip { new_content.push_str(line); new_content.push('\n'); } } else if !skip { new_content.push_str(line); new_content.push('\n'); } } if let Err(e) = std::fs::write("/etc/fail2ban/jail.local", new_content.trim()) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write: {}", e) })); } match run_shell("systemctl restart fail2ban") { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "warning": format!("Deleted but restart failed: {}", e) })), } } /// POST /api/security/fail2ban/config — save jail.local and restart fail2ban pub async fn security_fail2ban_config_save( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let content = body.get("content").and_then(|v| v.as_str()).unwrap_or(""); if content.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Content required" })); } if let Err(e) = std::fs::write("/etc/fail2ban/jail.local", content) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write: {}", e) })); } match run_shell("systemctl restart fail2ban") { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "warning": format!("Saved but restart failed: {}", e) })), } } /// POST /api/security/fail2ban/unban — unban an IP { "ip": "1.2.3.4", "jail": "sshd" } pub async fn security_fail2ban_unban( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let ip = body.get("ip").and_then(|v| v.as_str()).unwrap_or(""); let jail = body.get("jail").and_then(|v| v.as_str()).unwrap_or("sshd"); if ip.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "IP required" })); } // Sanitise IP — allow only digits, dots, colons (IPv6) if !ip.chars().all(|c| c.is_ascii_digit() || c == '.' || c == ':') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid IP" })); } // Sanitise jail name too — it goes into a shell command line, and jail // names are plain identifiers (fail2ban section names). if jail.is_empty() || !jail.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid jail" })); } match run_shell(&format!("fail2ban-client set {} unbanip {}", jail, ip)) { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/security/ufw/install — install UFW pub async fn security_ufw_install( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } match run_shell("apt-get update && apt-get install -y ufw") { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/security/ufw/rule — add a UFW rule { "rule": "allow 22/tcp" } pub async fn security_ufw_add_rule( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let rule = body.get("rule").and_then(|v| v.as_str()).unwrap_or(""); if rule.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Rule required" })); } // Basic sanitisation — only allow alphanumeric, spaces, slashes, dots, colons if !rule.chars().all(|c| c.is_alphanumeric() || c == ' ' || c == '/' || c == '.' || c == ':') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid rule characters" })); } match run_shell(&format!("ufw {}", rule)) { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/security/ufw/rule — delete a UFW rule { "rule_number": "3" } pub async fn security_ufw_delete_rule( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let num = body.get("rule_number").and_then(|v| v.as_str()).unwrap_or(""); if num.is_empty() || !num.chars().all(|c| c.is_ascii_digit()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Valid rule number required" })); } match run_shell(&format!("echo y | ufw delete {}", num)) { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// POST /api/security/ufw/toggle — enable or disable UFW { "enable": true } pub async fn security_ufw_toggle( _req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let enable = body.get("enable").and_then(|v| v.as_bool()).unwrap_or(false); let cmd = if enable { "echo y | ufw enable" } else { "ufw disable" }; match run_shell(cmd) { Ok(out) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/security/iptables/rules — get iptables rules pub async fn security_iptables_rules( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let rules = run_shell("iptables -L -n --line-numbers 2>/dev/null") .unwrap_or_else(|e| format!("Error: {}", e)); HttpResponse::Ok().json(serde_json::json!({ "rules": rules })) } /// POST /api/security/updates/check — refresh package cache and list pending updates pub async fn security_check_updates( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let (pkg_manager, output) = if command_exists("apt") { let _ = run_shell("apt-get update -qq 2>/dev/null"); let list = run_shell("apt list --upgradable 2>/dev/null | grep -v '^Listing'") .unwrap_or_default(); ("apt", list) } else if command_exists("dnf") { let list = run_shell("dnf check-update --quiet 2>/dev/null").unwrap_or_default(); ("dnf", list) } else if command_exists("yum") { let list = run_shell("yum check-update --quiet 2>/dev/null").unwrap_or_default(); ("yum", list) } else if command_exists("pacman") { let _ = run_shell("pacman -Sy 2>/dev/null"); let list = run_shell("pacman -Qu 2>/dev/null").unwrap_or_default(); ("pacman", list) } else { ("unknown", String::new()) }; let count = output.lines().filter(|l| !l.trim().is_empty()).count(); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "package_manager": pkg_manager, "count": count, "list": output.trim(), })) } /// POST /api/security/updates/apply — apply all pending updates pub async fn security_apply_updates( _req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&_req, &state) { return resp; } let cmd = if command_exists("apt") { "DEBIAN_FRONTEND=noninteractive apt-get upgrade -y 2>&1" } else if command_exists("dnf") { "dnf upgrade -y 2>&1" } else if command_exists("yum") { "yum update -y 2>&1" } else if command_exists("pacman") { "pacman -Syu --noconfirm 2>&1" } else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "No supported package manager found" })); }; // apt-get/dnf upgrade can run for minutes — run it on the blocking // pool, never inline on an actix-rt worker. Running it inline pins a // worker thread for the whole upgrade and degrades this node's HTTP / // peer-poll responsiveness (a contributor to the apply-node CPU peg). match web::block(move || run_shell(cmd)).await { Ok(Ok(out)) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "output": out })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("apply task failed: {}", e) })), } } // ─── Issues Scanner ─── /// Parse human-readable size strings (e.g. "1.2G", "450M", "32K") to MB fn parse_size_to_mb(s: &str) -> f64 { let s = s.trim(); if s.is_empty() { return 0.0; } let (num_str, suffix) = if s.ends_with(|c: char| c.is_alphabetic()) { let idx = s.len() - 1; (&s[..idx], &s[idx..]) } else { (s, "") }; let num: f64 = num_str.parse().unwrap_or(0.0); match suffix.to_uppercase().as_str() { "T" => num * 1024.0 * 1024.0, "G" => num * 1024.0, "M" => num, "K" => num / 1024.0, "B" => num / (1024.0 * 1024.0), _ => num, // assume MB } } #[derive(Serialize, Clone)] pub struct Issue { pub severity: String, // "critical", "warning", "info" pub category: String, // "cpu", "memory", "disk", "swap", "load", "service", "container" pub title: String, pub detail: String, } /// A one-click recovery the operator can run from the issues page for a /// fixable issue. `kind` selects the server-side recipe; `target` is the /// concrete thing it acts on (a systemd unit, or a fixed token like /// "journal"); `label` is the button text. Computed per-issue at scan /// time by [`repair_for`] rather than stored on every `Issue`, so the /// ~18 existing issue producers stay untouched. #[derive(Serialize, Clone)] pub struct IssueRepair { pub kind: String, // "service" | "clamav" | "chkrootkit" | "certbot" | "journal" | "apt" | "dnf" pub target: String, // unit name, or a fixed token for disk-cleanup kinds pub label: String, // button text: "Repair" | "Clean" } /// Classify a failed systemd unit into the repair recipe that actually /// recovers it. Service-specific where it matters, generic otherwise. fn repair_kind_for_unit(unit: &str) -> &'static str { let u = unit.to_ascii_lowercase(); if u.contains("clamav") || u.contains("freshclam") { "clamav" } else if u.contains("chkrootkit") { "chkrootkit" } else if u.contains("certbot") || u.contains("letsencrypt") { "certbot" } else { "service" } } /// Given an issue, return the repair the operator can run for it — or /// None when there's no safe one-click action (CPU/RAM/load/swap, k8s /// pods, and /tmp are deliberately excluded: /tmp may stage malware, so /// it's never auto-cleaned). Service units are parsed from the issue's /// `detail` ("systemd unit X is in failed state") and re-validated by /// `valid_unit_name`; the disk-cleanup kinds key off the `title` prefix /// (they carry no unit). Both couplings fail closed — if a producer string /// in `collect_issues` is reworded, the button simply doesn't appear /// rather than misfiring. pub fn repair_for(issue: &Issue) -> Option { match issue.category.as_str() { "service" => { let unit = issue.detail .strip_prefix("systemd unit ") .and_then(|s| s.strip_suffix(" is in failed state")) .map(|s| s.trim()) .filter(|s| valid_unit_name(s))?; Some(IssueRepair { kind: repair_kind_for_unit(unit).to_string(), target: unit.to_string(), label: "Repair".into(), }) } "disk" => { // Only the three caches we know how to clean safely. let (kind, target) = if issue.title.starts_with("Journal logs using") { ("journal", "journal") } else if issue.title.starts_with("APT cache") { ("apt", "apt") } else if issue.title.starts_with("DNF cache") { ("dnf", "dnf") } else { return None; // /tmp, low-disk warnings: no blind one-click }; Some(IssueRepair { kind: kind.into(), target: target.into(), label: "Clean".into() }) } _ => None, } } /// Collect system issues (reusable — called by HTTP handler and background scheduler) pub fn collect_issues(metrics: &crate::monitoring::SystemMetrics) -> Vec { let mut issues: Vec = Vec::new(); let mem_pct = metrics.memory_percent; // ── CPU check ── if metrics.cpu_usage_percent > 90.0 { issues.push(Issue { severity: "critical".into(), category: "cpu".into(), title: "CPU usage critically high".into(), detail: format!("CPU at {:.1}% — system may be unresponsive", metrics.cpu_usage_percent), }); } else if metrics.cpu_usage_percent > 75.0 { issues.push(Issue { severity: "warning".into(), category: "cpu".into(), title: "CPU usage elevated".into(), detail: format!("CPU at {:.1}% — monitor for sustained load", metrics.cpu_usage_percent), }); } // ── Memory check ── if mem_pct > 90.0 { issues.push(Issue { severity: "critical".into(), category: "memory".into(), title: "Memory usage critically high".into(), detail: format!("Memory at {:.1}% — OOM risk", mem_pct), }); } else if mem_pct > 80.0 { issues.push(Issue { severity: "warning".into(), category: "memory".into(), title: "Memory usage elevated".into(), detail: format!("Memory at {:.1}%", mem_pct), }); } // ── Disk checks (free space, not just %) ── for disk in &metrics.disks { // Skip /boot/ and /etc/pve mounts unless >99% — managed by the OS/Proxmox if (disk.mount_point.starts_with("/boot") || disk.mount_point == "/etc/pve") && disk.usage_percent <= 99.0 { continue; } let total_gb = disk.total_bytes as f64 / 1_073_741_824.0; let used_gb = disk.used_bytes as f64 / 1_073_741_824.0; let free_gb = disk.available_bytes as f64 / 1_073_741_824.0; let size_detail = format!("{} — {:.1} GB used / {:.1} GB total ({:.1} GB free, {:.1}%)", disk.mount_point, used_gb, total_gb, free_gb, disk.usage_percent); // Same size-scaled floor as the predictive disk finding, so the // Issues page and the alerts never disagree about whether a disk // is in trouble (the old flat 10 GB / 2 GB said nothing about a // 436 GB database disk until minutes before it filled). let (warn_floor, crit_floor) = crate::predictive::disk_verdict::free_space_floor_bytes(disk.total_bytes); if disk.available_bytes < crit_floor { issues.push(Issue { severity: "critical".into(), category: "disk".into(), title: format!("Disk {} almost full ({:.1} GB free)", disk.mount_point, free_gb), detail: size_detail, }); } else if disk.available_bytes < warn_floor { issues.push(Issue { severity: "warning".into(), category: "disk".into(), title: format!("Disk {} low on space ({:.1} GB free)", disk.mount_point, free_gb), detail: size_detail, }); } } // ── Failing physical disks (SMART) ── // The free-space loop above catches FULL disks; this catches DYING ones. // Uses the SAME evaluator the Storage page and the Issues alerting watcher // use (array::disk_smart_health + DiskSmart::failing_reasons — Backblaze // SMART 5/187/197/198, NVMe wear/spare, overall-health FAILED), so a drive // the operator sees reddened under Storage also shows up HERE, on the page // where they run upgrades (a failing SSD used to raise nothing on this scan // — collect_issues never checked disk health; PapaSchlumpf 2026-07-01). The // standby guard is gated on rotational-ness so an SSD/NVMe whose power-mode // probe can't confirm an active state is still read (never skipped), while a // spun-down HDD is left asleep. Physical-disk SMART is host-level and // independent of `metrics`, so it's read directly here. for dev in crate::array::list_physical_disks() { let guard = crate::array::disk_is_rotational(&dev); if let Some(health) = crate::array::disk_smart_health(&dev, guard) { let reasons = health.failing_reasons(); if !reasons.is_empty() { issues.push(Issue { severity: "critical".into(), category: "disk".into(), title: format!("Disk {} is failing (SMART)", dev), detail: format!("{} — back up and plan replacement: {}", dev, reasons.join("; ")), }); } } } // ── UPS battery needing replacement ── // Same verdict as the UPS page and the predictive finding // (ups::parse_upsc → replace_battery: NUT `RB` status flag or // battery.packs.bad > 0). Only the UPS this node is configured to // monitor is read; an unreadable UPS raises nothing here — the UPS // page already shows the comms error. let ups_target = crate::ups::UpsConfig::load().ups.trim().to_string(); if !ups_target.is_empty() && crate::ups::upsc_installed() && let Ok(live) = crate::ups::query_ups(&ups_target) && let Some(why) = crate::ups::battery_fault_summary(&live) { issues.push(Issue { severity: "critical".into(), category: "ups".into(), title: format!("UPS '{}' battery needs replacing", ups_target), detail: format!( "{} — the UPS may not hold the load through the next power cut; replace the battery", why, ), }); } // ── Swap check ── if metrics.swap_total_bytes > 0 { let swap_pct = (metrics.swap_used_bytes as f64 / metrics.swap_total_bytes as f64) * 100.0; if swap_pct > 50.0 { issues.push(Issue { severity: "warning".into(), category: "swap".into(), title: "Significant swap usage".into(), detail: format!("Swap at {:.1}% — system may be low on RAM", swap_pct), }); } } // ── Load average check ── let cpu_count = metrics.cpu_count.max(1) as f64; if metrics.load_avg.one > cpu_count * 2.0 { issues.push(Issue { severity: "critical".into(), category: "load".into(), title: "Load average extremely high".into(), detail: format!("Load {:.2} ({:.1}× CPU count {})", metrics.load_avg.one, metrics.load_avg.one / cpu_count, metrics.cpu_count), }); } else if metrics.load_avg.one > cpu_count { issues.push(Issue { severity: "warning".into(), category: "load".into(), title: "Load average high".into(), detail: format!("Load {:.2} (>{} CPUs)", metrics.load_avg.one, metrics.cpu_count), }); } // ── Failed systemd services ── if let Ok(output) = std::process::Command::new("systemctl") .args(["--failed", "--no-legend", "--plain"]) .output() { let stdout = String::from_utf8_lossy(&output.stdout); for line in stdout.lines() { let parts: Vec<&str> = line.split_whitespace().collect(); if let Some(unit) = parts.first() && !unit.is_empty() { issues.push(Issue { severity: "warning".into(), category: "service".into(), title: format!("Service {} failed", unit), detail: format!("systemd unit {} is in failed state", unit), }); } } } // ── Stopped Docker containers ── if let Ok(output) = std::process::Command::new("docker") .args(["ps", "-a", "--filter", "status=exited", "--format", "{{.Names}}"]) .output() { let stdout = String::from_utf8_lossy(&output.stdout); let stopped: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect(); if !stopped.is_empty() { issues.push(Issue { severity: "info".into(), category: "container".into(), title: format!("{} stopped Docker container(s)", stopped.len()), detail: format!("Stopped: {}", stopped.join(", ")), }); } } // ── Kubernetes cluster issues ── let k8s_clusters = crate::kubernetes::list_clusters(); for cluster in &k8s_clusters { let status = crate::kubernetes::get_cluster_status(&cluster.kubeconfig_path); if !status.healthy { issues.push(Issue { severity: "warning".into(), category: "kubernetes".into(), title: format!("K8s cluster '{}' unhealthy", cluster.name), detail: format!("{}/{} nodes ready, {}/{} pods running", status.nodes_ready, status.nodes_total, status.pods_running, status.pods_total), }); } // Check for NotReady nodes let nodes = crate::kubernetes::get_nodes(&cluster.kubeconfig_path); for n in &nodes { if n.status != "Ready" { issues.push(Issue { severity: "critical".into(), category: "kubernetes".into(), title: format!("K8s node '{}' not ready", n.name), detail: format!("Cluster '{}', status: {}, role: {}", cluster.name, n.status, n.roles), }); } } // Check for problem pods (exclude Succeeded/Completed pods — these are finished Jobs/init containers) let pods = crate::kubernetes::get_pods(&cluster.kubeconfig_path, None); let active_pods: Vec<_> = pods.iter().filter(|p| p.status != "Succeeded").collect(); let failed = active_pods.iter().filter(|p| p.status == "Failed" || p.status == "Unknown").count(); let pending = active_pods.iter().filter(|p| p.status == "Pending").count(); let high_restarts = active_pods.iter().filter(|p| p.restarts >= 10).count(); if failed > 0 { issues.push(Issue { severity: "critical".into(), category: "kubernetes".into(), title: format!("{} failed pod(s) in cluster '{}'", failed, cluster.name), detail: active_pods.iter().filter(|p| p.status == "Failed" || p.status == "Unknown") .take(5).map(|p| format!("{}/{}", p.namespace, p.name)).collect::>().join(", "), }); } if pending > 0 { issues.push(Issue { severity: "warning".into(), category: "kubernetes".into(), title: format!("{} pending pod(s) in cluster '{}'", pending, cluster.name), detail: active_pods.iter().filter(|p| p.status == "Pending") .take(5).map(|p| format!("{}/{}", p.namespace, p.name)).collect::>().join(", "), }); } if high_restarts > 0 { issues.push(Issue { severity: "warning".into(), category: "kubernetes".into(), title: format!("{} pod(s) with high restarts in cluster '{}'", high_restarts, cluster.name), detail: active_pods.iter().filter(|p| p.restarts >= 10) .take(5).map(|p| format!("{}/{} ({}x)", p.namespace, p.name, p.restarts)).collect::>().join(", "), }); } } // ── Clearable disk space ── // Journal logs if let Ok(output) = std::process::Command::new("journalctl") .args(["--disk-usage"]) .output() { let stdout = String::from_utf8_lossy(&output.stdout); // Parse "Archived and active journals take up 1.2G in the file system." if let Some(size_str) = stdout.split("take up ").nth(1).and_then(|s| s.split(' ').next()) { let size_mb = parse_size_to_mb(size_str); if size_mb > 500.0 { issues.push(Issue { severity: "info".into(), category: "disk".into(), title: format!("Journal logs using {}", size_str), detail: "Run 'journalctl --vacuum-size=200M' to reclaim space".to_string(), }); } } } // Package cache (apt) if let Ok(output) = std::process::Command::new("du") .args(["-sh", "/var/cache/apt/archives"]) .output() && output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); if let Some(size_str) = stdout.split_whitespace().next() { let size_mb = parse_size_to_mb(size_str); if size_mb > 200.0 { issues.push(Issue { severity: "info".into(), category: "disk".into(), title: format!("APT cache using {}", size_str), detail: "Run 'apt clean' to reclaim space".into(), }); } } } // Package cache (dnf/yum) if let Ok(output) = std::process::Command::new("du") .args(["-sh", "/var/cache/dnf"]) .output() && output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); if let Some(size_str) = stdout.split_whitespace().next() { let size_mb = parse_size_to_mb(size_str); if size_mb > 200.0 { issues.push(Issue { severity: "info".into(), category: "disk".into(), title: format!("DNF cache using {}", size_str), detail: "Run 'dnf clean all' to reclaim space".into(), }); } } } // /tmp usage if let Ok(output) = std::process::Command::new("du") .args(["-sh", "/tmp"]) .output() && output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); if let Some(size_str) = stdout.split_whitespace().next() { let size_mb = parse_size_to_mb(size_str); if size_mb > 500.0 { issues.push(Issue { severity: "info".into(), category: "disk".into(), title: format!("/tmp using {}", size_str), detail: "Temporary files may be safe to clean up".into(), }); } } } // Docker unused images if let Ok(output) = std::process::Command::new("docker") .args(["system", "df", "--format", "{{.Reclaimable}}"]) .output() && output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); // Sum up any reclaimable amounts let mut total_mb = 0.0f64; let mut total_str = String::new(); for line in stdout.lines() { let clean = line.trim().split('(').next().unwrap_or("").trim(); if !clean.is_empty() && clean != "0B" { let mb = parse_size_to_mb(clean); total_mb += mb; if total_str.is_empty() { total_str = clean.to_string(); } } } if total_mb > 500.0 { issues.push(Issue { severity: "info".into(), category: "container".into(), title: format!("Docker reclaimable space: {:.0} MB", total_mb), detail: "Run 'docker system prune' to reclaim unused images/containers".into(), }); } } issues } /// GET /api/issues/scan — scan system for issues pub async fn scan_issues( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Both the monitor sample AND collect_issues run on the blocking pool: // collect_issues shells out (systemctl, docker, journalctl, du) and now // also probes SMART (`timeout 10 smartctl` per physical disk), so it must // never run on the actix worker thread. let st = state.clone().into_inner(); let (metrics, issues) = tokio::task::spawn_blocking(move || { let metrics = st.monitor.lock().unwrap().collect(); let issues = collect_issues(&metrics); (metrics, issues) }).await.unwrap(); // Enrich each issue with its one-click repair (when one exists) without // bloating the Issue struct or its ~18 producers. Serialising the issue // and grafting `repair` on keeps the wire shape additive — older nodes // simply omit the field and the frontend treats them as non-repairable. let issues_json: Vec = issues.iter().map(|i| { let mut v = serde_json::to_value(i).unwrap_or_else(|_| serde_json::json!({})); if let Some(rep) = repair_for(i) && let Ok(rv) = serde_json::to_value(&rep) { v["repair"] = rv; } v }).collect(); HttpResponse::Ok().json(serde_json::json!({ "hostname": metrics.hostname, "version": env!("CARGO_PKG_VERSION"), "issues": issues_json, "ai_analysis": null, })) } /// GET /api/alerts?since=ID — get recent alerts for the Tasks window pub async fn get_alert_log( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let since_id: u64 = query.get("since") .and_then(|s| s.parse().ok()) .unwrap_or(0); let log = state.alert_log.read().unwrap(); let new_entries: Vec<&AlertLogEntry> = log.iter() .filter(|e| e.id > since_id) .collect(); HttpResponse::Ok().json(serde_json::json!({ "alerts": new_entries, })) } /// GET /api/alerts/history — paginated, filterable view over the /// same in-memory alert log used by `get_alert_log`. Drives the /// Alerts page → History sub-tab. Optional query params: /// - `severity` — filter exact match ("critical" / "warning" / ...) /// - `cluster` — filter exact match /// - `host` — filter exact match on hostname /// - `q` — case-insensitive substring match on title + detail /// - `since` — return only entries with id > since /// - `limit` — max rows to return; default 200, clamped to 1000 /// /// Response shape: /// `{ alerts: [...], total: N, returned: N, oldest_id, newest_id }` /// Frontend uses `oldest_id` as the next page cursor (set `since=oldest_id - 1` /// won't work for forward paging; instead the History page just /// re-queries with adjusted filters). pub async fn get_alert_history( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let severity = query.get("severity").cloned(); let cluster = query.get("cluster").cloned(); let host = query.get("host").cloned(); let q_lower = query.get("q").map(|s| s.to_lowercase()); let since_id: u64 = query.get("since").and_then(|s| s.parse().ok()).unwrap_or(0); let limit: usize = query.get("limit") .and_then(|s| s.parse().ok()) .unwrap_or(200) .min(1000); // Merge sources: state.alert_log (array health / AI critical / // gateway audit — the legacy v23 writers) AND the new in-memory // alerting::history_snapshot (every send_node_alert dispatch as // of v24). The two sources have disjoint contents in practice; // unified shape is the existing AlertLogEntry. Newest-first. let legacy_log = state.alert_log.read().unwrap(); let legacy_rows: Vec = legacy_log.iter().cloned().collect(); drop(legacy_log); let history_rows: Vec = crate::alerting::history_snapshot() .into_iter() .map(|h| AlertLogEntry { // Offset the history ID range so it doesn't collide with // the legacy log's IDs (which start at 1 from the // process-lifetime start). 1_000_000+ is a safe band — // legacy log capped at 200, so it can never reach it. id: 1_000_000 + h.id, timestamp: h.timestamp, severity: h.severity, title: h.title, detail: h.detail, hostname: h.hostname, cluster: h.cluster, }) .collect(); // Combined newest-first ordering by timestamp string (RFC3339, // lexicographically sortable for the modern entries; legacy uses // a different format but is bounded to 200 rows so the imperfect // ordering near the boundary is acceptable). let mut all: Vec = legacy_rows.into_iter() .chain(history_rows) .collect(); all.sort_by(|a, b| b.timestamp.cmp(&a.timestamp)); let matched: Vec = all.into_iter() .filter(|e| e.id > since_id) .filter(|e| severity.as_deref().is_none_or(|s| e.severity == s)) .filter(|e| cluster.as_deref().is_none_or(|c| e.cluster == c)) .filter(|e| host.as_deref().is_none_or(|h| e.hostname == h)) .filter(|e| q_lower.as_deref().is_none_or(|q| { e.title.to_lowercase().contains(q) || e.detail.to_lowercase().contains(q) })) .collect(); let total = matched.len(); let mut truncated = matched; truncated.truncate(limit); let returned = truncated.len(); let newest_id = truncated.first().map(|e| e.id).unwrap_or(0); let oldest_id = truncated.last().map(|e| e.id).unwrap_or(0); HttpResponse::Ok().json(serde_json::json!({ "alerts": truncated, "total": total, "returned": returned, "newest_id": newest_id, "oldest_id": oldest_id, })) } /// GET /api/settings/paths — get file location configuration pub async fn get_file_locations( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::paths::get()) } /// POST /api/settings/paths — update file location configuration pub async fn update_file_locations( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match crate::paths::update(body.into_inner()) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({"success": true})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// Vacuum the systemd journal to 200 MB; returns MB freed (≥0). Shared by /// the Issues "Clean" bulk action and the per-issue repair so both stay in /// lockstep if the target size or journalctl output format ever changes. fn reclaim_journal_mb() -> f64 { let read_mb = || run_shell("journalctl --disk-usage 2>/dev/null").ok() .and_then(|o| o.split("take up ").nth(1).and_then(|s| s.split(' ').next()).map(parse_size_to_mb)); let before = read_mb().unwrap_or(0.0); let _ = run_shell("journalctl --vacuum-size=200M 2>/dev/null"); let after = read_mb().unwrap_or(before); (before - after).max(0.0) } /// Clean the APT archive cache + autoremove; returns MB freed (≥0). /// Caller must confirm `apt` exists. Shared with [`clean_system`]. fn reclaim_apt_mb() -> f64 { let read_mb = || run_shell("du -sm /var/cache/apt/archives 2>/dev/null").ok() .and_then(|o| o.split_whitespace().next().and_then(|s| s.parse::().ok())); let before = read_mb().unwrap_or(0.0); let _ = run_shell("apt-get clean -y 2>/dev/null"); let _ = run_shell("apt-get autoremove -y 2>/dev/null"); let after = read_mb().unwrap_or(0.0); (before - after).max(0.0) } /// Clean the DNF cache; returns MB freed (≥0). Caller must confirm `dnf` /// exists. Shared with [`clean_system`]. fn reclaim_dnf_mb() -> f64 { let read_mb = || run_shell("du -sm /var/cache/dnf 2>/dev/null").ok() .and_then(|o| o.split_whitespace().next().and_then(|s| s.parse::().ok())); let before = read_mb().unwrap_or(0.0); let _ = run_shell("dnf clean all 2>/dev/null"); let after = read_mb().unwrap_or(0.0); (before - after).max(0.0) } /// POST /api/issues/clean — run safe cleanup to free disk space pub async fn clean_system( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut cleaned = Vec::new(); let mut total_freed_mb: f64 = 0.0; // ── Journal logs → vacuum to 200M ── let jfreed = reclaim_journal_mb(); if jfreed > 1.0 { total_freed_mb += jfreed; cleaned.push(format!("Journal logs: freed {:.0} MB", jfreed)); } // ── APT cache ── if command_exists("apt") { let afreed = reclaim_apt_mb(); if afreed > 1.0 { total_freed_mb += afreed; cleaned.push(format!("APT cache: freed {:.0} MB", afreed)); } } // ── DNF/YUM cache ── if command_exists("dnf") { let dfreed = reclaim_dnf_mb(); if dfreed > 1.0 { total_freed_mb += dfreed; cleaned.push(format!("DNF cache: freed {:.0} MB", dfreed)); } } else if command_exists("yum") { let _ = run_shell("yum clean all 2>/dev/null"); cleaned.push("YUM cache: cleaned".into()); } // ── Old kernels (keep current + 1 previous) ── if command_exists("apt") { let out = run_shell("dpkg -l 'linux-image-*' 2>/dev/null | grep '^ii' | awk '{print $2}' | grep -v $(uname -r | sed 's/-generic//') | head -5").ok().unwrap_or_default(); let old_kernels: Vec<&str> = out.lines().filter(|l| !l.is_empty() && l.contains("linux-image")).collect(); if !old_kernels.is_empty() { for kernel in &old_kernels { let _ = run_shell(&format!("DEBIAN_FRONTEND=noninteractive apt-get remove -y {} 2>/dev/null", kernel)); } cleaned.push(format!("Old kernels: removed {} package(s)", old_kernels.len())); } } // ── Docker prune ── if command_exists("docker") { let out = run_shell("docker system prune -f 2>/dev/null").ok().unwrap_or_default(); // Parse "Total reclaimed space: 1.23GB" from output if let Some(line) = out.lines().find(|l| l.contains("reclaimed space")) && let Some(size_str) = line.split(": ").nth(1) { let mb = parse_size_to_mb(size_str.trim()); if mb > 1.0 { total_freed_mb += mb; cleaned.push(format!("Docker prune: freed {}", size_str.trim())); } } } // ── /tmp old files (>7 days) ── let _ = run_shell("find /tmp -type f -atime +7 -delete 2>/dev/null"); if cleaned.is_empty() { cleaned.push("System is already clean — nothing to free.".into()); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "cleaned": cleaned, "freed_mb": total_freed_mb.round() as u64, })) } /// Strict allowlist for a systemd unit name before it is ever handed to /// `systemctl`. This is the security boundary for `/api/issues/repair`: /// the unit arrives from the client, so we never interpolate it into a /// shell and we never accept anything that isn't a plain unit name. /// Allowed chars match systemd's own (`[A-Za-z0-9:_.\-@\]`) plus a hard /// length cap and a required known unit suffix; everything else (spaces, /// `/`, `;`, `&`, `$`, `..`, globs) is rejected. fn valid_unit_name(unit: &str) -> bool { if unit.is_empty() || unit.len() > 128 { return false; } let suffix_ok = [ ".service", ".timer", ".socket", ".target", ".mount", ".path", ".scope", ".slice", ].iter().any(|s| unit.ends_with(s)); if !suffix_ok { return false; } unit.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '_' | '.' | '-' | '@' | '\\')) } /// True iff systemd currently reports `unit` as failed. Doubles as an /// authorisation gate for repair: we only ever act on units that are /// genuinely in the failed state the operator was shown — this endpoint /// can't be repurposed to restart or poke arbitrary running services. fn unit_is_failed(unit: &str) -> bool { std::process::Command::new("systemctl") .arg("is-failed") .arg(unit) .output() .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "failed") .unwrap_or(false) } #[derive(serde::Deserialize)] pub struct RepairRequest { pub kind: String, pub target: String, } /// POST /api/issues/repair — run the one-click recovery for a single /// issue surfaced by `/api/issues/scan`. `kind` picks the recipe and /// `target` is the unit (for service kinds) or a fixed token (for the /// disk-cleanup kinds). Every service action goes through /// [`valid_unit_name`] + [`unit_is_failed`] and is executed with argv /// (never a shell), so a hostile `target` cannot inject a command or /// touch a healthy service. pub async fn repair_issue( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let kind = body.kind.clone(); let target = body.target.clone(); let result = web::block(move || run_repair(&kind, &target)).await; match result { Ok(Ok(payload)) => HttpResponse::Ok().json(payload), Ok(Err(msg)) => HttpResponse::BadRequest().json(serde_json::json!({"ok": false, "error": msg})), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"ok": false, "error": format!("repair task failed: {}", e)})), } } /// Blocking core of [`repair_issue`]. Returns the JSON payload on success /// or a human-readable error string (surfaced as 400) on bad input. All /// subprocess work is argv-based. fn run_repair(kind: &str, target: &str) -> Result { // Helpers — argv only, capture combined stdout/stderr tail. fn systemctl(args: &[&str]) -> (bool, String) { match std::process::Command::new("systemctl").args(args).output() { Ok(o) => { let mut out = String::from_utf8_lossy(&o.stdout).to_string(); out.push_str(&String::from_utf8_lossy(&o.stderr)); (o.status.success(), out.trim().to_string()) } Err(e) => (false, format!("failed to run systemctl: {}", e)), } } match kind { // ── Disk cleanups: fixed targets, no unit, no shell interpolation. // Share the exact reclaim helpers used by /api/issues/clean so // the bulk and per-issue paths can never drift. ── "journal" => { let freed = reclaim_journal_mb(); Ok(serde_json::json!({ "ok": true, "kind": kind, "target": "journal", "action": "Vacuumed systemd journal to 200 MB", "log": format!("Freed {:.0} MB.", freed), })) } "apt" => { if !command_exists("apt") { return Err("apt is not available on this host".into()); } let freed = reclaim_apt_mb(); Ok(serde_json::json!({ "ok": true, "kind": kind, "target": "apt", "action": "Cleaned APT cache", "log": format!("apt-get clean + autoremove freed {:.0} MB.", freed), })) } "dnf" => { if !command_exists("dnf") { return Err("dnf is not available on this host".into()); } let freed = reclaim_dnf_mb(); Ok(serde_json::json!({ "ok": true, "kind": kind, "target": "dnf", "action": "Cleaned DNF cache", "log": format!("dnf clean all freed {:.0} MB.", freed), })) } // ── Service recipes: target is a unit and must pass the gate ── "service" | "clamav" | "chkrootkit" | "certbot" => { if !valid_unit_name(target) { return Err(format!("'{}' is not a valid systemd unit name", target)); } if !unit_is_failed(target) { // Already healthy (operator may have fixed it, or another // repair raced us). Clear any lingering failed marker and // report success rather than churning the unit. let _ = systemctl(&["reset-failed", target]); return Ok(serde_json::json!({ "ok": true, "kind": kind, "target": target, "action": "No action needed", "log": format!("{} is not in a failed state.", target), })); } let (action, log) = match kind { "clamav" => { // Rebuild signatures (ensures clamav user, runs freshclam, // verifies DB) then clear the failed marker. let r = crate::antivirus::repair_clamav_signatures(); let _ = systemctl(&["reset-failed", target]); let (_ok, restart_log) = systemctl(&["restart", target]); let summary = match &r.error { None => format!( "freshclam ok: {}, signatures present: {}{}", r.freshclam_ok, r.signatures_present_after, if r.healed_user { ", created missing clamav user" } else { "" }, ), Some(e) => format!("ClamAV repair reported: {}", e), }; ( "Rebuilt ClamAV signature DB and restarted unit".to_string(), format!("{}\n{}", summary, restart_log), ) } "chkrootkit" => { // chkrootkit.service exits non-zero on systemd false // positives (bindshell on 465/mosh, Linux/Ebury via // `ssh -G`, /sbin/init Suckit). We clear the failed // state but do NOT auto-suppress findings — the operator // is told to cross-check with rkhunter. let (_ok, l) = systemctl(&["reset-failed", target]); ( "Cleared chkrootkit failed state".to_string(), format!("chkrootkit.service commonly false-positives on systemd hosts. \ Cleared the failed marker; cross-check with `rkhunter --check` if unsure.\n{}", l), ) } "certbot" => { // Resolve certbot through the same probe the certbot // module uses. A bare `which` runs under systemd's PATH, // which carries neither /snap/bin nor pipx/venv installs, // so a snap host reported "not on PATH" and skipped the // renew even though certbot was right there. // // No --quiet: this run exists to TELL the operator why the // unit failed, and the distro's own certbot.service already // runs `certbot -q renew`, whose silence is what sent them // here. stdout and stderr are both kept, on success and on // failure alike — the previous `run_shell(..).unwrap_or_default()` // threw the output away on a non-zero exit, blanking the // panel in exactly the case worth reading. let renew_note = match crate::certbot::certbot_path() { Some(bin) => match std::process::Command::new(&bin) .args(["renew", "--non-interactive"]) .output() { Ok(out) => { let mut text = String::from_utf8_lossy(&out.stdout).into_owned(); text.push_str(&String::from_utf8_lossy(&out.stderr)); let text = text.trim().to_string(); match (out.status.success(), text.is_empty()) { (true, true) => "certbot renew: no certificates were due for renewal.".to_string(), (true, false) => text, (false, true) => format!( "certbot renew failed ({}) with no output — see /var/log/letsencrypt/letsencrypt.log.", out.status, ), (false, false) => format!( "certbot renew failed ({}):\n{}\n\nFull detail: /var/log/letsencrypt/letsencrypt.log", out.status, text, ), } } Err(e) => format!("could not run {}: {}", bin, e), }, None => crate::certbot::missing_certbot_error(), }; let _ = systemctl(&["reset-failed", target]); let (_ok, restart_log) = systemctl(&["restart", target]); ( "Cleared failed state and restarted unit".to_string(), format!("{}\n{}", renew_note, restart_log), ) } _ => { // Generic: clear the failed marker then restart. let _ = systemctl(&["reset-failed", target]); let (ok, restart_log) = systemctl(&["restart", target]); ( if ok { "Reset and restarted unit".to_string() } else { "Reset failed; restart did not succeed".to_string() }, restart_log, ) } }; // Report the post-repair truth so the UI doesn't claim success // on a unit that immediately re-failed. let still_failed = unit_is_failed(target); Ok(serde_json::json!({ "ok": !still_failed, "kind": kind, "target": target, "action": action, "log": log, "still_failed": still_failed, })) } other => Err(format!("unknown repair kind '{}'", other)), } } // ═══════════════════════════════════════════════ // ─── Alerting & Notifications ─── // ═══════════════════════════════════════════════ pub async fn alerts_config_get(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::alerting::AlertConfig::load(); let mut json = config.to_masked_json(); // Email is a delivery path like the others, but its transport lives on // AiConfig — so the Alerts page had no way to show that alerts were also // being mailed, which is how an operator ends up paged twice with nothing // on screen explaining the second copy. Report whether it's set up (and // where to configure it), never the address itself. let email_cfg = crate::ai::AiConfig::load(); if let Some(obj) = json.as_object_mut() { obj.insert( "has_email".to_string(), serde_json::Value::Bool(email_cfg.email_enabled && !email_cfg.email_to.is_empty()), ); } HttpResponse::Ok().json(json) } pub async fn alerts_config_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::alerting::AlertConfig::load(); let v = body.into_inner(); if let Some(enabled) = v.get("enabled").and_then(|v| v.as_bool()) { config.enabled = enabled; } if let Some(url) = v.get("discord_webhook").and_then(|v| v.as_str()) { config.discord_webhook = url.to_string(); } if let Some(url) = v.get("slack_webhook").and_then(|v| v.as_str()) { config.slack_webhook = url.to_string(); } if let Some(token) = v.get("telegram_bot_token").and_then(|v| v.as_str()) { config.telegram_bot_token = token.to_string(); } if let Some(id) = v.get("telegram_chat_id").and_then(|v| v.as_str()) { config.telegram_chat_id = id.to_string(); } if let Some(t) = v.get("cpu_threshold").and_then(|v| v.as_f64()) { config.cpu_threshold = t as f32; } if let Some(t) = v.get("memory_threshold").and_then(|v| v.as_f64()) { config.memory_threshold = t as f32; } if let Some(t) = v.get("disk_threshold").and_then(|v| v.as_f64()) { config.disk_threshold = t as f32; } if let Some(b) = v.get("alert_node_offline").and_then(|v| v.as_bool()) { config.alert_node_offline = b; } if let Some(b) = v.get("alert_node_restored").and_then(|v| v.as_bool()) { config.alert_node_restored = b; } if let Some(b) = v.get("alert_cpu").and_then(|v| v.as_bool()) { config.alert_cpu = b; } if let Some(b) = v.get("alert_memory").and_then(|v| v.as_bool()) { config.alert_memory = b; } if let Some(b) = v.get("alert_disk").and_then(|v| v.as_bool()) { config.alert_disk = b; } // Container monitoring toggle + threshold — these were MISSING here, so // unchecking "Container memory alert" never persisted and reverted to on // after Save (wabil 2026-06-21). if let Some(b) = v.get("alert_containers").and_then(|v| v.as_bool()) { config.alert_containers = b; } if let Some(t) = v.get("container_memory_threshold").and_then(|v| v.as_f64()) { config.container_memory_threshold = t as f32; } if let Some(i) = v.get("check_interval_secs").and_then(|v| v.as_u64()) { // Clamp to sensible range: 30 seconds to 1 hour config.check_interval_secs = i.clamp(30, 3600); } if let Some(i) = v.get("security_scan_interval_secs").and_then(|v| v.as_u64()) { // Clamp to 1 hour minimum (matches the UI dropdown floor) and // 24 hours maximum to keep at least one scan per day even if // a user picks the highest setting offered. config.security_scan_interval_secs = i.clamp(3600, 24 * 3600); } // Notification verbosity. Anything other than the exact string // "verbose" falls back to Simple — defensive against typos and // forward-compatible with future verbosity tiers if we ever add one. if let Some(s) = v.get("alert_verbosity").and_then(|v| v.as_str()) { config.alert_verbosity = match s { "verbose" => crate::alerting::AlertVerbosity::Verbose, _ => crate::alerting::AlertVerbosity::Simple, }; } // ── v24.0.0: Schedule sub-tab fields ─────────────────────────── if let Some(qh) = v.get("quiet_hours") { // The frontend posts either an object or `null`/missing. // `null` clears the window; object replaces wholesale. if qh.is_null() { config.quiet_hours = None; } else if let Ok(parsed) = serde_json::from_value::(qh.clone()) { config.quiet_hours = Some(parsed); } } if let Some(i) = v.get("cooldown_secs").and_then(|v| v.as_u64()) { // Floor at 60s — cooldown shorter than that defeats the purpose // and risks alert storms. Ceiling at 24h to keep it usable. config.cooldown_secs = i.clamp(60, 24 * 3600); } if let Some(i) = v.get("max_alerts_per_hour").and_then(|v| v.as_u64()) { // 0 = no cap. Ceiling at 10_000 to avoid integer surprises. config.max_alerts_per_hour = i.min(10_000) as u32; } if let Some(i) = v.get("grouping_window_secs").and_then(|v| v.as_u64()) { // 0 = grouping off; max 30 min (longer windows make the // group notification stale). config.grouping_window_secs = i.min(30 * 60); } if let Some(s) = v.get("grouping_strategy").and_then(|v| v.as_str()) { config.grouping_strategy = match s { "by_guest" => crate::alerting::GroupingStrategy::ByGuest, _ => crate::alerting::GroupingStrategy::ByNode, }; } if let Some(b) = v.get("recovery_notifications").and_then(|v| v.as_bool()) { config.recovery_notifications = b; } // Discord bot token is write-only from the UI's perspective — // masked in to_masked_json so the frontend never sees it back. // Only overwrite when a non-empty value arrives, so a save with // the field blank doesn't wipe a previously-configured token. if let Some(t) = v.get("discord_bot_token").and_then(|v| v.as_str()) { let trimmed = t.trim(); if !trimmed.is_empty() { config.discord_bot_token = trimmed.to_string(); } } // Telegram receiver flag — boolean. No secret-handling special- // casing; the *token* is already in telegram_bot_token (long- // standing outbound field). if let Some(b) = v.get("telegram_receiver_enabled").and_then(|v| v.as_bool()) { config.telegram_receiver_enabled = b; } if let Some(s) = v.get("twilio_account_sid").and_then(|v| v.as_str()) { config.twilio_account_sid = s.trim().to_string(); } // Twilio auth token: write-only, same shape as discord_bot_token. if let Some(t) = v.get("twilio_auth_token").and_then(|v| v.as_str()) { let trimmed = t.trim(); if !trimmed.is_empty() { config.twilio_auth_token = trimmed.to_string(); } } if let Some(s) = v.get("twilio_whatsapp_from").and_then(|v| v.as_str()) { config.twilio_whatsapp_from = s.trim().to_string(); } // ntfy server — plain config (not a secret). Blank resets to the // public instance so a cleared field can't leave the channel // pointing at "". if let Some(s) = v.get("ntfy_server").and_then(|v| v.as_str()) { let trimmed = s.trim().trim_end_matches('/'); config.ntfy_server = if trimmed.is_empty() { "https://ntfy.sh".to_string() } else { trimmed.to_string() }; } // ntfy topic + token: masked in to_masked_json (on the public // server the topic name IS the credential), so same write-only // shape as discord_bot_token — only overwrite on non-empty input // so a save with the field blank keeps the stored value. if let Some(t) = v.get("ntfy_topic").and_then(|v| v.as_str()) { let trimmed = t.trim(); if !trimmed.is_empty() { config.ntfy_topic = trimmed.to_string(); } } if let Some(t) = v.get("ntfy_token").and_then(|v| v.as_str()) { let trimmed = t.trim(); if !trimmed.is_empty() { config.ntfy_token = trimmed.to_string(); } } // Explicit disconnect — distinct from "left blank" above. The UI's // "Disable ntfy" button sends this to clear the channel. if v.get("ntfy_clear").and_then(|v| v.as_bool()) == Some(true) { config.ntfy_topic = String::new(); config.ntfy_token = String::new(); } // Apprise. The server address, tag and username are plain config; the // stateless URLs (they hold the destinations' own credentials), the // config key and the password are write-only, kept when sent blank. // `apprise_mode` is the form's radio — "key", "urls" or "server" (the // server's own APPRISE_STATELESS_URLS) — and decides which of the two // stored values survives, so switching modes never leaves both set. // Errors name their field so the form can mark it. let apprise_err = |field: &str, msg: &str| HttpResponse::BadRequest() .json(serde_json::json!({ "error": msg, "field": field })); if let Some(s) = v.get("apprise_url").and_then(|v| v.as_str()) { let trimmed = s.trim().trim_end_matches('/'); if !trimmed.is_empty() && let Some(problem) = crate::alerting::apprise_server_problem(trimmed) { return apprise_err("apprise_url", problem); } config.apprise_url = trimmed.to_string(); } let new_urls = v.get("apprise_urls").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()); let new_key = v.get("apprise_key").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()); if new_urls.is_some() && new_key.is_some() { return apprise_err("apprise_key", "Give Apprise either URLs or a configuration key, not both."); } if let Some(urls) = new_urls { config.apprise_urls = urls.to_string(); config.apprise_key = String::new(); } if let Some(key) = new_key { if let Some(problem) = crate::alerting::apprise_key_problem(key) { return apprise_err("apprise_key", problem); } config.apprise_key = key.to_string(); config.apprise_urls = String::new(); } match v.get("apprise_mode").and_then(|v| v.as_str()) { Some("server") => { config.apprise_key = String::new(); config.apprise_urls = String::new(); } Some("key") => { config.apprise_urls = String::new(); if !config.apprise_url.is_empty() && config.apprise_key.is_empty() { return apprise_err("apprise_key", "Enter the Apprise configuration key, or pick another way to send."); } } Some("urls") => { config.apprise_key = String::new(); if !config.apprise_url.is_empty() && config.apprise_urls.is_empty() { return apprise_err("apprise_urls", "Enter at least one Apprise URL, or pick another way to send."); } } _ => {} } if let Some(s) = v.get("apprise_tag").and_then(|v| v.as_str()) { config.apprise_tag = s.trim().to_string(); } if let Some(s) = v.get("apprise_user").and_then(|v| v.as_str()) { let user = s.trim(); // Apprise refuses a username containing ':' (APPRISE_USER), and // Basic Auth could not carry one unambiguously anyway. if user.contains(':') { return apprise_err("apprise_user", "The Apprise username can't contain ':'."); } config.apprise_user = user.to_string(); } if let Some(t) = v.get("apprise_password").and_then(|v| v.as_str()) && !t.is_empty() { // Not trimmed: a password may legitimately end in a space. config.apprise_password = t.to_string(); } // Explicit disconnect — the "Disable Apprise" button. if v.get("apprise_clear").and_then(|v| v.as_bool()) == Some(true) { config.apprise_url = String::new(); config.apprise_urls = String::new(); config.apprise_key = String::new(); config.apprise_tag = String::new(); config.apprise_user = String::new(); config.apprise_password = String::new(); } // Delivery-path selection: an array of channel names ("ntfy", "email", …). // An empty array means "every configured channel" — the pre-selection // behaviour — so the UI can offer "all of them" without a magic value. // Unknown names are dropped rather than defaulted: quietly adding a path // the operator didn't ask for is the exact complaint this setting fixes. if let Some(arr) = v.get("channels").and_then(|v| v.as_array()) { config.channels = crate::alerting::Channel::parse_list( arr.iter().filter_map(|c| c.as_str()), ); } match config.save() { Ok(()) => { // Alert settings are shared across the cluster: stamp this save // as the newest version and copy it to the other nodes. alert_settings_changed(&state); HttpResponse::Ok().json(serde_json::json!({ "saved": true })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Alert settings as carried between nodes by "copy to every node in /// this cluster". `email` is present only when the source node has /// alert email switched on — copying a disabled email setup would turn /// email OFF on a peer that has its own, which is never what pressing /// "copy" means. #[derive(serde::Serialize, serde::Deserialize)] pub struct AlertSettingsBundle { pub alert_config: crate::alerting::AlertConfig, #[serde(default)] pub email: Option, } /// Unix milliseconds — the unit of `AlertConfig::shared_rev`. fn alert_rev_now() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0) } /// This node's saved alert settings, plus alert email when it is on here. fn alert_settings_bundle() -> AlertSettingsBundle { let alert_config = crate::alerting::AlertConfig::load(); let ai = crate::ai::AiConfig::load(); let email = (ai.email_enabled && !ai.email_to.trim().is_empty()) .then(|| ai.email_transport()); AlertSettingsBundle { alert_config, email } } /// The WolfStack peers alert settings go to. `all_clusters` = every node this /// node manages; otherwise only its own cluster — the same boundary the AI / /// SMTP settings sync keeps, because the payload carries the SMTP password and /// a multi-cluster manager may hold other operators' fleets. fn alert_settings_peers(cluster: &crate::agent::ClusterState, all_clusters: bool) -> Vec { let nodes = cluster.get_all_nodes(); let self_cluster = nodes.iter().find(|n| n.is_self).and_then(|n| n.cluster_name.clone()); nodes.into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack") .filter(|n| all_clusters || crate::agent::same_display_cluster(n.cluster_name.as_deref(), self_cluster.as_deref())) .collect() } /// HTTPS, then the encrypted WolfNet link. The plain-HTTP fallback /// `build_node_urls` offers for ordinary peer calls is deliberately not used: /// these calls carry webhook URLs and the SMTP password. fn alert_settings_urls(peer: &crate::agent::Node, path: &str) -> Vec { let mut urls = vec![format!( "https://{}:{}{}", crate::netaddr::bracket_host(&peer.address), peer.port, path, )]; if let Some(wn) = lookup_node_wolfnet_ip(&peer.address) { urls.push(format!("http://{}:{}{}", wn, peer.port + 1, path)); } urls } /// Send `bundle` to one peer. Ok(()) when it saved it. async fn push_alert_settings_to( peer: &crate::agent::Node, secret: &str, bundle: &AlertSettingsBundle, ) -> Result<(), String> { let client = (*API_HTTP_CLIENT).clone(); let mut last_err = String::from("unreachable"); for url in alert_settings_urls(peer, "/api/alerts/config/peer-apply") { match client.post(&url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(secret) .json(bundle) .send().await { Ok(resp) if resp.status().is_success() => { let _ = resp.bytes().await; return Ok(()); } Ok(resp) => { let code = resp.status(); let body = resp.text().await.unwrap_or_default(); // A 404 means the peer runs a WolfStack from before this // endpoint existed — say so instead of a bare status. return Err(if code == reqwest::StatusCode::NOT_FOUND { "peer's WolfStack is too old for this — upgrade it first".to_string() } else if code == reqwest::StatusCode::CONFLICT { "peer already has newer alert settings (saved there more recently) — not replaced".to_string() } else { format!("HTTP {}: {}", code.as_u16(), body.chars().take(200).collect::()) }); } Err(e) => last_err = e.to_string(), } } Err(last_err) } /// Ask a peer which alert-settings version it holds. None = unreachable, or a /// WolfStack too old to say (it will be brought in line once it upgrades). async fn peer_alert_settings_rev(peer: &crate::agent::Node, secret: &str) -> Option { let client = (*API_HTTP_CLIENT).clone(); for url in alert_settings_urls(peer, "/api/alerts/config/rev") { if let Ok(resp) = client.get(&url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(secret) .send().await { if !resp.status().is_success() { // Drain so the connection is released (see tests/resource_safety.rs). let _ = resp.bytes().await; return None; } let v: serde_json::Value = resp.json().await.ok()?; return v.get("rev").and_then(|r| r.as_u64()); } } None } /// Push this node's alert settings to every peer in scope and report per node. async fn push_alert_settings( cluster: &crate::agent::ClusterState, secret: &str, all_clusters: bool, ) -> (bool, Vec) { let bundle = match tokio::task::spawn_blocking(alert_settings_bundle).await { Ok(b) => b, Err(e) => return (false, vec![serde_json::json!({ "ok": false, "error": e.to_string() })]), }; let email_copied = bundle.email.is_some(); let mut results = Vec::new(); for peer in alert_settings_peers(cluster, all_clusters) { let label = if peer.hostname.is_empty() { peer.address.clone() } else { peer.hostname.clone() }; let cluster_label = peer.cluster_name.clone().unwrap_or_else(|| "WolfStack".to_string()); let outcome = if peer.online { push_alert_settings_to(&peer, secret, &bundle).await } else { Err("offline — it will be updated automatically once it is back".to_string()) }; results.push(match outcome { Ok(()) => serde_json::json!({ "node_id": peer.id, "hostname": label, "cluster": cluster_label, "ok": true }), Err(e) => serde_json::json!({ "node_id": peer.id, "hostname": label, "cluster": cluster_label, "ok": false, "error": e }), }); } (email_copied, results) } /// Background reconcile, run every few minutes from `main.rs`: alert settings /// are per node, and until 2026-11-23 they only spread when someone pressed /// "copy" — so wolfstack-2/3 sat with alerting off while the operator believed /// it was on everywhere. Now every node in a cluster converges on the most /// recently saved settings: a node offers its copy to any same-cluster peer /// holding an older version. Offline nodes and nodes that join later catch up /// on a later pass. A node that was never configured (version 0) offers /// nothing, so it can never blank out a configured one. pub async fn alert_settings_reconcile(cluster: &crate::agent::ClusterState, secret: &str) { let rev = tokio::task::spawn_blocking(|| crate::alerting::AlertConfig::load().effective_shared_rev()) .await.unwrap_or(0); if rev == 0 { return; } let mut bundle: Option = None; for peer in alert_settings_peers(cluster, false).into_iter().filter(|p| p.online) { let Some(peer_rev) = peer_alert_settings_rev(&peer, secret).await else { continue }; if peer_rev >= rev { continue; } if bundle.is_none() { bundle = tokio::task::spawn_blocking(alert_settings_bundle).await.ok(); } let Some(b) = bundle.as_ref() else { return }; match push_alert_settings_to(&peer, secret, b).await { Ok(()) => tracing::info!("alert settings copied to '{}' (it had an older version)", peer.hostname), Err(e) => tracing::warn!("could not copy alert settings to '{}': {}", peer.hostname, e), } } } /// Record an operator save of the shared alert settings (alert rules or alert /// email) and copy it to the rest of this node's cluster in the background. /// The reconcile pass retries anyone this misses. pub fn alert_settings_changed(state: &web::Data) { let mut cfg = crate::alerting::AlertConfig::load(); cfg.shared_rev = alert_rev_now(); if let Err(e) = cfg.save() { tracing::warn!("could not record alert settings version: {e}"); return; } let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { let (_, results) = push_alert_settings(&cluster, &secret, false).await; for r in results.iter().filter(|r| r["ok"] != true) { tracing::warn!("alert settings not yet copied to {}: {}", r["hostname"], r["error"]); } }); } /// POST /api/alerts/config/copy-to-cluster — push this node's alert /// settings (and alert email, when on) to every other WolfStack node in /// the same cluster now, and report per node. Same-cluster copying also /// happens automatically on every save; this button is the visible, /// reported version. `?scope=all` widens it to every WolfStack node this /// node manages, in every cluster: the region servers sit in their own /// cluster, and that crossing is never automatic (see /// `alert_settings_peers`). #[derive(Deserialize)] pub struct CopyAlertsQuery { /// "all" = every managed cluster; anything else (or absent) = this /// node's own cluster only. #[serde(default)] pub scope: Option, } pub async fn alerts_config_copy_to_cluster( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let all_clusters = query.scope.as_deref() == Some("all"); // Pressing copy means "these are the settings": make them the newest // version so peers accept them and the reconcile keeps them in place. let stamped = web::block(|| { let mut cfg = crate::alerting::AlertConfig::load(); cfg.shared_rev = alert_rev_now(); cfg.save() }).await; if let Ok(Err(e)) | Err(e) = stamped.map_err(|e| e.to_string()) { return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("could not read local settings: {}", e) })); } let (email_copied, results) = push_alert_settings(&state.cluster, &state.cluster_secret, all_clusters).await; HttpResponse::Ok().json(serde_json::json!({ "cluster": local_cluster_name(&state.cluster), "all_clusters": all_clusters, "email_copied": email_copied, "results": results, })) } /// GET /api/alerts/config/rev — which alert-settings version this node holds. /// Cluster-secret only; carries no settings. pub async fn alerts_config_rev(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let rev = web::block(|| crate::alerting::AlertConfig::load().effective_shared_rev()) .await.unwrap_or(0); HttpResponse::Ok().json(serde_json::json!({ "rev": rev })) } /// POST /api/alerts/config/peer-apply — receive alert settings from a /// cluster peer (see `push_alert_settings`). Cluster-secret only: this /// writes webhook URLs and the SMTP password. /// /// Refuses (409) settings older than the ones held here, so a node that was /// offline during a save can't push its stale copy back over the new one. /// Version 0 (a sender from before versioning) is accepted, as the copy /// button always was. pub async fn alerts_config_peer_apply( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_secret(&req, &state) { return resp; } let bundle = body.into_inner(); let email = bundle.email.clone(); let res = web::block(move || -> Result { let mut cfg = crate::alerting::AlertConfig::load(); let incoming = bundle.alert_config.shared_rev; if incoming != 0 && incoming < cfg.shared_rev { return Ok(false); } cfg.adopt_shared_settings(&bundle.alert_config); cfg.save()?; if let Some(email) = bundle.email { let mut ai = crate::ai::AiConfig::load(); ai.set_email_transport(email); ai.save()?; } Ok(true) }).await; match res { Ok(Ok(true)) => { // The AI settings page saves from the in-memory copy; without // this, the next save there would write the old email back over // what was just received. if let Some(email) = email { let mut ai = state.ai_agent.config.lock().unwrap_or_else(|e| e.into_inner()); ai.set_email_transport(email); } tracing::info!("alert settings updated from a cluster peer"); HttpResponse::Ok().json(serde_json::json!({ "saved": true })) } Ok(Ok(false)) => HttpResponse::Conflict().json(serde_json::json!({ "error": "this node holds newer alert settings", })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } pub async fn alerts_test(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::alerting::AlertConfig::load(); config.enabled = true; // Force enable for test let results = crate::alerting::send_test(&config).await; let ok_count = results.iter().filter(|r| r.succeeded()).count(); let details: Vec = results.iter().map(|r| { serde_json::json!({ "channel": r.channel.as_str(), "success": r.succeeded(), // Configured but not a selected delivery path: nothing was sent, // and a real alert wouldn't go there either. The UI says so // rather than showing it as a failure. "skipped": r.skipped, "error": r.error(), }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "sent": ok_count, "results": details, })) } // ─── System package install ─── #[derive(Deserialize)] pub struct InstallPackageRequest { /// Logical package name from the allowlist in /// `crate::installer::packages` — `cron`, `qemu`, etc. The /// per-distro mapping happens server-side; the caller never sees /// the actual apt/pacman name. pub package: String, } /// POST /api/system/install-package — install a system package by /// its WolfStack-internal logical name. Used by the System Check UI's /// "Install" button when a dependency is missing. Restricted to the /// fixed allowlist server-side so the endpoint can't be abused as a /// generic apt/pacman shell. Runs the install synchronously off the /// async executor since package managers are blocking subprocesses. /// /// Authorisation: `require_auth` refuses read-only (viewer) sessions /// every unsafe method, so a viewer gets 403 here — the gap VolkSec /// reported on 2026-09-09 (CWE-862). The allowlist is defence in depth, /// not the authorisation boundary. pub async fn system_install_package( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let pkg = body.into_inner().package; let result = tokio::task::spawn_blocking(move || { crate::installer::packages::install(&pkg) }).await; match result { Ok(Ok(report)) => HttpResponse::Ok().json(serde_json::json!({ "success": report.success, "package": report.package, "binary": report.binary, "message": report.message, "service_started": report.service_started, })), Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "success": false, "error": e, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "success": false, "error": format!("install task panicked: {}", e), })), } } // ─── Predictive ops: Inbox + Acknowledgements ──────────────────── // // Surfaces the proposal store (analyzer findings) and the ack store // (operator-declared "this is intentional, stop firing") to the // frontend Inbox view. All endpoints require a session cookie; the // underlying store is `Arc>` in AppState so reads and // writes are cheap and the orchestrator background loop owns // long-held locks only inside spawn_blocking. /// GET /api/proposals — inbox view (Pending + active Snoozed), /// sorted Critical→Info, then most-recently-updated first. /// /// Acked findings are filtered out at read time. Without this the /// "Ack as intentional" button only stops *future* analyser runs /// from re-creating the proposal; the existing Pending row would /// stay visible forever (Piranha bug, 2026-05-04). pub async fn predictive_proposals_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let acks = state.predictive_acks.read().unwrap_or_else(|e| e.into_inner()).clone(); let store = state.predictive_proposals.read().unwrap_or_else(|e| e.into_inner()); let inbox: Vec = store.inbox().into_iter() .filter(|p| !acks.suppresses(&p.finding_type, &p.scope)) .cloned() .collect(); HttpResponse::Ok().json(inbox) } /// GET /api/proposals/cluster — aggregated inbox across this node /// and every reachable cluster peer. /// /// Cached for 30 s (`cluster::CACHE_TTL_SECS`) so a dashboard /// refresh doesn't translate into one HTTP fan-out per peer per /// refresh. Cache is invalidated on every state-changing predictive /// endpoint so operator actions produce immediately-visible /// feedback. /// /// Per-peer fetch failures are surfaced in the `nodes` field so the /// UI can warn that the Inbox is incomplete instead of silently /// showing partial data. pub async fn predictive_proposals_cluster( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Cache hit? { let cache = state.predictive_cluster_cache.lock() .unwrap_or_else(|e| e.into_inner()); if let Some((value, ts)) = &*cache { let age = ts.elapsed().as_secs(); if age < crate::predictive::cluster::CACHE_TTL_SECS { let mut response = value.clone(); response.cached_for_seconds = age; return HttpResponse::Ok().json(response); } } } // Cache miss — fan out. let response = build_cluster_response(&state).await; // Save back. Stale-on-poison falls through to a fresh build next // time, which is the conservative choice. { let mut cache = state.predictive_cluster_cache.lock() .unwrap_or_else(|e| e.into_inner()); *cache = Some((response.clone(), std::time::Instant::now())); } HttpResponse::Ok().json(response) } async fn build_cluster_response( state: &web::Data, ) -> crate::predictive::cluster::ClusterProposalsResponse { use crate::predictive::cluster::{ ClusterProposalsResponse, NodeAggregateStatus, sort_proposals, }; // Self proposals — clone out under a brief read lock. Filter // against the local ack store so already-acked findings stay // hidden when the operator re-opens the inbox (Piranha bug — // ack only stopped *future* analyser runs from re-creating). let acks = state.predictive_acks.read().unwrap_or_else(|e| e.into_inner()).clone(); let self_proposals: Vec = { let store = state.predictive_proposals.read() .unwrap_or_else(|e| e.into_inner()); store.inbox().into_iter() .filter(|p| !acks.suppresses(&p.finding_type, &p.scope)) .cloned() .collect() }; // Self status — for the nodes list. We always responded to // ourselves; that's a tautology worth surfacing so the UI never // shows fewer entries than the cluster has nodes. let nodes_snapshot = state.cluster.get_all_nodes(); let self_node = nodes_snapshot.iter().find(|n| n.is_self).cloned(); let self_status = NodeAggregateStatus { node_id: state.node_id.clone(), hostname: self_node.as_ref().map(|n| n.hostname.clone()).unwrap_or_default(), is_self: true, responded: true, error: None, cluster_name: self_node.as_ref().map(resolve_cluster_label).unwrap_or_default(), }; // Peers — only online wolfstack nodes that aren't ourselves. // Proxmox-typed nodes don't run our analyzer so we skip them. let peers: Vec<_> = nodes_snapshot.into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack" && n.online) .collect(); // Fan-out — one task per peer, each with its own timeout. We // collect the JoinHandles then await them with `tokio::join!` / // `futures::join_all`-style sequence. Using FuturesUnordered // would be tidier; for a small N this is fine. // Each handle carries (node_id, hostname, cluster) so panics // still identify the peer. The `node_id` here MUST match what // the peer's own predictive orchestrator stamps onto // `Proposal.scope.node_id` — otherwise the cluster filter in // the Inbox UI maps the proposal to the wrong cluster and the // list goes empty when the operator picks a non-default // cluster. // // Each peer's orchestrator uses the local `state.node_id`, // which is the value of `/etc/wolfstack/node_id` (the peer's // *self_id*). Locally we know that as `peer.self_id` (Option), // populated when the peer first reports. Falls back to // `peer.id` (the locally-assigned cluster key) for peers that // haven't reported a self_id yet. let secret = state.cluster_secret.clone(); type ProposalFetch = tokio::task::JoinHandle, String>>; let mut handles: Vec<(String, String, String, ProposalFetch)> = Vec::with_capacity(peers.len()); for peer in &peers { let urls = build_node_urls(&peer.address, peer.port, "/api/proposals"); let secret = secret.clone(); let cluster = resolve_cluster_label(peer); let canonical_id = peer.self_id.clone().unwrap_or_else(|| peer.id.clone()); let handle = tokio::spawn(async move { fetch_peer_proposals(&urls, &secret).await }); handles.push((canonical_id, peer.hostname.clone(), cluster, handle)); } let mut all_proposals = self_proposals; let mut node_status: Vec = vec![self_status]; for (id, hostname, cluster_name, h) in handles { match h.await { Ok(Ok(proposals)) => { all_proposals.extend( proposals.into_iter() .filter(|p| !acks.suppresses(&p.finding_type, &p.scope)) ); node_status.push(NodeAggregateStatus { node_id: id, hostname, is_self: false, responded: true, error: None, cluster_name, }); } Ok(Err(e)) => { node_status.push(NodeAggregateStatus { node_id: id, hostname, is_self: false, responded: false, error: Some(e), cluster_name, }); } Err(e) => { tracing::warn!( "predictive cluster: peer task for {} ({}) panicked: {}", id, hostname, e, ); node_status.push(NodeAggregateStatus { node_id: id, hostname, is_self: false, responded: false, error: Some(format!("task panic: {}", e)), cluster_name, }); } } } sort_proposals(&mut all_proposals); ClusterProposalsResponse { proposals: all_proposals, nodes: node_status, cached_for_seconds: 0, } } /// Fetch a peer's `/api/proposals` using inter-node auth. Returns a /// short, operator-readable error string on any failure mode so the /// UI's "node not responded" tooltip is meaningful. async fn fetch_peer_proposals( urls: &[String], secret: &str, ) -> Result, String> { let mut last_status_err: Option = None; for url in urls { let send = API_HTTP_CLIENT .get(url) .peer_auth(secret) .send(); match tokio::time::timeout(crate::predictive::cluster::PEER_FETCH_TIMEOUT, send).await { Err(_) => return Err("timeout".to_string()), Ok(Err(_)) => continue, // connection refused / TLS fail / etc — try next URL Ok(Ok(resp)) => { let status = resp.status(); if status.is_success() { return resp.json::>().await .map_err(|e| format!("invalid response shape: {}", e)); } if status == 401 || status == 403 { return Err(format!("auth rejected (HTTP {})", status.as_u16())); } if status == 404 { return Err("peer doesn't expose /api/proposals (older version?)".to_string()); } last_status_err = Some(format!("HTTP {}", status.as_u16())); continue; } } } Err(last_status_err.unwrap_or_else(|| "no URL reachable".to_string())) } /// Resolve a `Node` to the cluster grouping label used by the /// dashboard. Mirrors the rule in `web/js/app.js`: /// /// - Proxmox-typed nodes prefer `pve_cluster_name`, then their /// own `cluster_name`, then their `address` (so a standalone /// PVE host shows under its hostname/IP). /// - WolfStack-typed nodes use `cluster_name` falling back to /// `"WolfStack"` for older nodes that never set one. /// /// Lifted into Rust so the predictive Inbox aggregator groups by /// cluster the same way the rest of the UI does. fn resolve_cluster_label(node: &crate::agent::Node) -> String { if node.node_type == "proxmox" { node.pve_cluster_name.clone() .or_else(|| node.cluster_name.clone()) .filter(|s| !s.is_empty()) .unwrap_or_else(|| node.address.clone()) } else { node.cluster_name.clone() .filter(|s| !s.is_empty()) .unwrap_or_else(|| "WolfStack".to_string()) } } /// Drop the cluster-aggregation cache so the next /// `/api/proposals/cluster` call rebuilds from scratch. Called from /// every state-changing predictive endpoint. fn invalidate_cluster_cache(state: &web::Data) { if let Ok(mut g) = state.predictive_cluster_cache.lock() { *g = None; } } /// GET /api/proposals/history — every proposal regardless of status /// (for the audit/history view). pub async fn predictive_proposals_history( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let store = match state.predictive_proposals.read() { Ok(g) => g, Err(e) => e.into_inner(), }; HttpResponse::Ok().json(&store.proposals) } /// GET /api/proposals/{id} — single proposal detail. pub async fn predictive_proposal_get( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let store = match state.predictive_proposals.read() { Ok(g) => g, Err(e) => e.into_inner(), }; match store.get(&id) { Some(p) => HttpResponse::Ok().json(p), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found" })), } } #[derive(Deserialize)] pub struct SnoozeProposalRequest { /// Snooze duration. Clamped to 1h..720h (30d) — silent forever /// is what Dismiss is for. pub hours: i64, } pub async fn predictive_proposal_snooze( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let hours = body.into_inner().hours.clamp(1, 24 * 30); let until = chrono::Utc::now() + chrono::Duration::hours(hours); let result = { let mut store = match state.predictive_proposals.write() { Ok(g) => g, Err(e) => e.into_inner(), }; let result = store.snooze(&id, until); if result.is_ok() { // Persist before releasing the lock and invalidating the cache. let _ = store.save(); } result }; match result { Ok(()) => { // Order matters: save first (so on-disk is fresh), then // invalidate the cluster cache. The opposite order races // — a concurrent /api/proposals/cluster could rebuild // and re-cache the stale state in the gap. invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true, "until": until.to_rfc3339(), })) } Err(_) => { // Cross-node: the proposal lives on a peer. Forward the // POST to its origin so the peer's local store records // the snooze. Without this, Snooze on any peer-owned // proposal silently 404s — the dashboard surfaces every // proposal cluster-wide via the aggregate, so operators // have no way of knowing they're looking at a peer-owned // one until they click an action and see it fail. // Cycle-breaker: a forwarded peer request must not re-fan-out // (see `is_inter_node_forward`). if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } forward_proposal_action_to_peers(&state, &id, "snooze", serde_json::json!({ "hours": hours }), is_operator_request(&caller)).await } } } #[derive(Deserialize)] pub struct DismissProposalRequest { /// Reason captured for audit + AI feedback. Required (non-empty /// after trim) so dismissals carry context the next analyzer /// run can learn from. pub reason: String, } pub async fn predictive_proposal_dismiss( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let reason = body.into_inner().reason.trim().to_string(); if reason.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "dismiss reason is required so the audit trail \ and AI feedback have something to learn from", })); } let result = { let mut store = match state.predictive_proposals.write() { Ok(g) => g, Err(e) => e.into_inner(), }; let result = store.dismiss(&id, reason.clone()); if result.is_ok() { // Persist before releasing the lock and invalidating the cache. let _ = store.save(); } result }; match result { Ok(()) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } Err(_) => { // Cycle-breaker: a forwarded peer request must not re-fan-out // (see `is_inter_node_forward`). if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } forward_proposal_action_to_peers(&state, &id, "dismiss", serde_json::json!({ "reason": reason }), is_operator_request(&caller)).await } } } /// POST /api/proposals/{id}/restore — undo a Dismiss or Snooze: the /// finding goes back to Pending and shows in the inbox again. Forwarded to /// the owning peer like the other proposal actions. pub async fn predictive_proposal_restore( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let result = { let mut store = match state.predictive_proposals.write() { Ok(g) => g, Err(e) => e.into_inner(), }; if store.get(&id).is_none() { None } else { let r = store.restore(&id); if r.is_ok() { // Persist before releasing the lock and invalidating the cache. let _ = store.save(); } Some(r) } }; match result { Some(Ok(())) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } // Owned here but not dismissed/snoozed — nothing to forward. Some(Err(e)) => HttpResponse::Conflict().json(serde_json::json!({ "error": e })), None => { // Cycle-breaker: a forwarded peer request must not re-fan-out // (see `is_inter_node_forward`). if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } let resp = forward_proposal_action_to_peers(&state, &id, "restore", serde_json::json!({}), is_operator_request(&caller)).await; // The owning peer dropped its own cache; ours still holds the // aggregate without this finding, and the UI reloads straight // after a restore — it would stay hidden for up to 30 s. if resp.status().is_success() { invalidate_cluster_cache(&state); } resp } } } /// POST /api/proposals/{id}/approve — record that the operator /// applied the remediation. v1 proposals are always /// `RemediationPlan::Manual`, so "approve" means "I ran the /// commands, mark this done"; v2 OneClick proposals will dispatch /// to a handler instead. pub async fn predictive_proposal_approve( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let result = { let mut store = match state.predictive_proposals.write() { Ok(g) => g, Err(e) => e.into_inner(), }; let result = store.record_approval(&id, crate::predictive::ApprovalOutcome::Applied); if result.is_ok() { // Persist before releasing the lock and invalidating the cache. let _ = store.save(); } result }; match result { Ok(()) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } Err(_) => { // Cycle-breaker: a forwarded peer request must not re-fan-out // (see `is_inter_node_forward`) — that recursion is the // fleet-wide CPU storm on "Mark applied". if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } forward_proposal_action_to_peers(&state, &id, "approve", serde_json::json!({}), is_operator_request(&caller)).await } } } /// The compiled-in one-click actions `POST /api/proposals/{id}/apply` can run. #[derive(Debug, Clone, PartialEq)] enum OneClickAction { /// Stop and mask rpcbind (`predictive::rpcbind`). LockDownRpcbind, /// Quarantine the container a compromise finding is about. Quarantine { target_key: String, kill: crate::quarantine::KillSpec }, /// Lift a container's quarantine. ReleaseQuarantine { target_key: String }, } /// Which one-click action, if any, a finding carries. Decided by finding /// type and scope only — never by text from the proposal or the request. fn one_click_action(p: &crate::predictive::Proposal) -> Option { use crate::predictive::intrusion; if crate::predictive::rpcbind::is_rpcbind_exposure(p) { return Some(OneClickAction::LockDownRpcbind); } let (target_key, _) = intrusion::parse_resource(p.scope.resource_id.as_deref()?)?; // The host is never a quarantine target. if target_key == intrusion::targets::HOST_KEY { return None; } if p.finding_type == intrusion::FT_QUARANTINED { return Some(OneClickAction::ReleaseQuarantine { target_key: target_key.to_string() }); } let kill = intrusion::quarantine_kill_spec(&p.finding_type)?; Some(OneClickAction::Quarantine { target_key: target_key.to_string(), kill }) } /// POST /api/proposals/{id}/apply — run the finding's one-click action. /// /// Three exist, each a fixed sequence chosen by finding type: /// /// * the `rpcbind-portmap` exposure (`predictive::rpcbind`): the analyzer had /// flagged an open portmapper on public-facing hosts since it shipped, and /// ours stayed open until a CERT-Bund notice arrived via the hosting /// provider's abuse desk; /// * **Quarantine** on a container-scoped `compromise_indicator:*` finding /// (`crate::quarantine`) — what an operator would do by hand to a /// compromised container: cut its network from the host side, /// freeze/capture/kill the processes the finding names; /// * **Release** on that container's quarantine card. /// /// Deliberately NOT a generic "run this proposal's commands" endpoint. /// Nothing from the proposal store or the request body is ever executed — /// the optional body only carries the operator's name when a peer forwards /// the action, for the security log. Every other finding is refused, so a /// new analyzer can't accidentally become executable and a direct API call /// can't turn an arbitrary remediation recipe into a shell. pub async fn predictive_proposal_apply( req: HttpRequest, state: web::Data, path: web::Path, body: web::Bytes, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); // Who to attribute the action to. A forward from the origin node // authenticates as "cluster-node"; the origin names its operator in // the body. Informational only — the cluster secret is the authority. let actor = if is_inter_node_forward(&caller) { serde_json::from_slice::(&body).ok() .and_then(|v| v.get("actor").and_then(|a| a.as_str()).map(|a| { // Persisted into the quarantine record and logged: printable, // bounded, nothing that could forge a log line. let clean: String = a.chars().filter(|c| !c.is_control()).take(64).collect(); format!("{} (via peer)", clean) })) .unwrap_or_else(|| caller.clone()) } else { caller.clone() }; // The action must run on the node that owns the finding, so a proposal this // node doesn't have goes to the same peer/federation fan-out that approve, // dismiss and snooze use. let owned = { let store = match state.predictive_proposals.read() { Ok(g) => g, Err(e) => e.into_inner(), }; store.get(&id).cloned() }; let Some(proposal) = owned else { // Cycle-breaker: a forwarded peer request must not re-fan-out // (see `is_inter_node_forward`). if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } return forward_proposal_action_to_peers(&state, &id, "apply", serde_json::json!({ "actor": caller }), is_operator_request(&caller)).await; }; let Some(action) = one_click_action(&proposal) else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "this finding has no one-click action — follow its \ remediation steps, which the inbox shows in full", })); }; // Host work (systemctl, nft, nsenter, signals) off the async executor. let reason = proposal.title.clone(); let actor_for_block = actor.clone(); let action_for_block = action.clone(); // (message, warning). A warning — quarantine left part of the container // connected, or could not stop a process cleanly — is returned beside // the success so the UI shows it in a dialog that must be read. let outcome: Result<(String, Option), String> = web::block(move || match action_for_block { OneClickAction::LockDownRpcbind => crate::predictive::rpcbind::lock_down().map(|m| (m, None)), OneClickAction::Quarantine { target_key, kill } => crate::quarantine::quarantine(&target_key, kill, &actor_for_block, &reason) .map(|o| (o.message, o.warning)), OneClickAction::ReleaseQuarantine { target_key } => crate::quarantine::release(&target_key, &actor_for_block).map(|m| (m, None)), }) .await .unwrap_or_else(|e| Err(format!("apply task failed to run: {}", e))); match outcome { Ok((message, warning)) => { // What the action means for the card: // * rpcbind locked down → the finding is fixed (Applied); // * quarantine → the compromise is CONTAINED, not fixed: the card // stays pending (a separate "quarantined" card appears); // * release → the quarantine card's condition is gone. Recorded // as ConditionCleared, not Applied, because Applied suppresses // the finding for 12 h and would hide a re-quarantine. let record = match &action { OneClickAction::LockDownRpcbind => Some(crate::predictive::ApprovalOutcome::Applied), OneClickAction::Quarantine { .. } => None, OneClickAction::ReleaseQuarantine { .. } => Some(crate::predictive::ApprovalOutcome::ConditionCleared), }; if let Some(outcome) = record { let mut store = match state.predictive_proposals.write() { Ok(g) => g, Err(e) => e.into_inner(), }; let _ = store.record_approval(&id, outcome); let _ = store.save(); } invalidate_cluster_cache(&state); tracing::info!("proposal {} applied by {}: {}", id, actor, message); HttpResponse::Ok().json(serde_json::json!({ "success": true, "message": message, "warning": warning })) } Err(error) => { // Nothing is recorded on a refusal or a failure. `record_approval` // moves a proposal to Approved whatever the outcome, which would // take a STILL-EXPOSED port out of the inbox — the finding has to // stay pending until it is actually closed. tracing::warn!("proposal {} apply refused for {}: {}", id, actor, error); HttpResponse::Conflict().json(serde_json::json!({ "error": error })) } } } /// True when a proposal action (approve / snooze / dismiss / history) /// arrived from a cluster peer rather than from the operator's browser /// — i.e. it was authenticated with the inter-node secret, so /// `require_auth` returned the `"cluster-node"` sentinel. /// /// Such a request is ITSELF a forward emitted by the origin node's /// `forward_proposal_action_to_peers` / `forward_proposal_get_to_peers`. /// If this node doesn't own the proposal it must record nothing and /// must NOT fan out again. Re-forwarding here is what turned a single /// "Mark applied" on a peer-owned proposal into a recursive, fleet-wide /// request cascade: every non-owner peer re-forwarded to all ITS peers /// (including the sender, with no visited-set or depth limit), which on /// a multi-node cluster pegged CPU across the fleet and "cycled" /// between nodes. The operator's origin node is the single fan-out /// point; peers only ever record locally or 404. Mirrors the /// `caller == "cluster-node"` cycle-breaker already used by the /// threat-intel and gateway fan-out endpoints. fn is_inter_node_forward(caller: &str) -> bool { caller == "cluster-node" } /// True when a request came directly from a logged-in operator (a /// browser session), as opposed to a relayed forward — either an /// intra-cluster one (`"cluster-node"`, via the cluster secret) or a /// federation relay (`"apikey:"`, via `Bearer wsk_…`). /// /// Only operator-originated actions are allowed to fan OUT to FEDERATED /// clusters. A relayed action must NOT re-federate: the operator's /// origin node already forwards directly to every federation it knows, /// so a federation's entry node re-federating reaches nothing new and /// risks an A→B→A ping-pong between two mutually-federated clusters /// (bounded only by the per-hop HTTP timeout). The entry node still /// fans out to its own LOCAL peers — that's how it reaches the owner /// within its cluster — it just stops there. fn is_operator_request(caller: &str) -> bool { !is_inter_node_forward(caller) && !caller.starts_with("apikey:") } /// POST /api/proposals/{id}/{action} fan-out fallback. Tries every /// online wolfstack peer in turn using the cluster secret, returning /// on the first 2xx response (or 404 if no peer owns the /// proposal). Used by snooze / dismiss / approve when the local /// store doesn't have the id — i.e. the proposal lives on a peer /// and the operator is acting from the cluster-aggregate inbox. /// /// Each peer's own handler will record the action AND invalidate /// its own cluster cache, so a subsequent `/api/proposals/cluster` /// from any node sees fresh state. /// /// `include_federations` gates the cross-cluster hop: pass `true` only /// for an operator-originated action (see `is_operator_request`). A /// relayed forward passes `false` so it reaches its own local peers but /// never re-federates — closing the A→B→A loop between two /// mutually-federated clusters. async fn forward_proposal_action_to_peers( state: &web::Data, proposal_id: &str, action: &str, body: serde_json::Value, include_federations: bool, ) -> HttpResponse { let path = format!("/api/proposals/{}/{}", urlencoding::encode(proposal_id), urlencoding::encode(action)); let body_bytes = serde_json::to_vec(&body).unwrap_or_default(); // ─── Local-cluster peers (X-WolfStack-Secret) ─── let peers: Vec<_> = state.cluster.get_all_nodes().into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack" && n.online) .collect(); let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; for peer in &peers { for url in build_node_urls(&peer.address, peer.port, &path) { let res = client.post(&url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&secret) .header("content-type", "application/json") .body(body_bytes.clone()) .send() .await; let Ok(resp) = res else { continue; }; let status = resp.status(); if status.is_success() { if let Ok(v) = resp.json::().await { return HttpResponse::Ok().json(v); } return HttpResponse::Ok().json(serde_json::json!({ "success": true })); } // 404 means this peer doesn't own the proposal — try next. // Other errors (5xx, auth) are also "try next" because the // operator wants ANY peer to succeed; we'll surface a final // not-found if every peer rejects. let _ = resp.bytes().await; } } // ─── Federated clusters (Bearer wsk_…) ─── // Each federation's entry node, on a local miss, fans out to its // own local peers (via the secret) — so forwarding once per // federation reaches every node it owns. We only take this hop for // operator-originated actions; a relayed forward sets // include_federations=false so it never re-federates (anti-loop — // see `is_operator_request`). let federations: Vec = if include_federations { let s = state.federations.read().unwrap_or_else(|e| e.into_inner()); s.clusters.clone() } else { Vec::new() }; for fc in federations { // build_client/insecure_tls handling lives inside federation::*; // we reach for a small helper here because fetch_json is GET-only. // Keep this duplication local to avoid widening federation's // public surface for one caller. let url = format!("{}{}", fc.base_url, path); let cli = build_federation_client(fc.insecure_tls); let res = cli.post(&url) .timeout(std::time::Duration::from_secs(10)) .header("Authorization", format!("Bearer {}", fc.api_key)) .header("content-type", "application/json") .body(body_bytes.clone()) .send() .await; let Ok(resp) = res else { continue; }; if resp.status().is_success() { if let Ok(v) = resp.json::().await { return HttpResponse::Ok().json(v); } return HttpResponse::Ok().json(serde_json::json!({ "success": true })); } let _ = resp.bytes().await; } HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on any reachable cluster peer or federated cluster" })) } /// Reqwest client mirror of `federation::build_client`. Federation's /// helper is private and only used by GET; we inline a copy here so /// the POST fan-out path can re-use the same TLS-skip behaviour /// without exporting a new public function from federation/. fn build_federation_client(insecure_tls: bool) -> reqwest::Client { let mut b = reqwest::Client::builder() // Bound the CONNECT — see tests/resource_safety.rs .connect_timeout(std::time::Duration::from_secs(5)) .timeout(std::time::Duration::from_secs(10)); if insecure_tls { b = b.danger_accept_invalid_certs(true); } b.build().unwrap_or_else(|_| reqwest::Client::new()) } /// GET /api/proposals/{id}/command/{idx} — return one of a /// proposal's `Manual` remediation commands plus the resolved /// console target (type + name, plus remote `node_id` when the /// finding lives on a peer). Used by the Inbox UI's Run button: /// the dashboard opens `console.html` with these values, the page /// fetches the command via this endpoint, and writes it to the /// PTY's stdin so the operator drops into an interactive session /// with the suggested command pre-run. /// /// Auth-gated. The command itself comes from the analyzer's /// proposal store on disk (never user-supplied), so URL injection /// can't smuggle in arbitrary shell — the command index is bounded /// by the proposal's recorded list. pub async fn predictive_proposal_command( req: HttpRequest, state: web::Data, path: web::Path<(String, usize)>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (id, idx) = path.into_inner(); let t = match resolve_proposal_target(&id, &state).await { Ok(t) => t, Err(resp) => return resp, }; let cmds = match &t.proposal.remediation { crate::predictive::RemediationPlan::Manual { commands, .. } => commands, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "proposal has no Manual remediation commands", })), }; let Some(command) = cmds.get(idx) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "command index out of range", })); }; HttpResponse::Ok().json(serde_json::json!({ "command": command, "console_type": t.console_type, "console_name": t.console_name, "remote_node_id": t.remote_node_id, "node_hostname": t.node_hostname, "title": t.proposal.title, })) } /// A proposal plus its resolved console target — the shared result of /// looking a proposal up (locally, then across peers) and mapping its /// scope to a console session. Both the per-index `command` endpoint /// and the `autofix-command` endpoint need exactly this, so it lives /// in one place rather than being duplicated. struct ResolvedProposalTarget { proposal: crate::predictive::Proposal, console_type: String, console_name: String, remote_node_id: Option, node_hostname: String, } /// Look a proposal up (local store first, then fan out to online peers /// — the Inbox aggregates proposals from every cluster node) and /// resolve its console target. On failure returns a ready-to-send /// error response. async fn resolve_proposal_target( id: &str, state: &web::Data, ) -> Result { // 1. Try local store. let local_p: Option = { let store = state.predictive_proposals.read() .unwrap_or_else(|e| e.into_inner()); store.get(id).cloned() }; // 2. If not local, fan out to online peers via X-WolfStack-Secret. let p = match local_p { Some(p) => p, None => match fetch_proposal_from_peers(id, state).await { Some(p) => p, None => return Err(HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found", }))), }, }; // Remediation commands run in the HOST shell of the finding's node, // whatever the scope. Every analyzer writes its recipe for the host // (`lxc-attach -n -- apt-get …`, `docker pull …`, `docker logs …`, // `qemu-img info …`), so running it in the container's own console // typed `lxc-attach` into the container: "command not found", nothing // updated, every LXC update card stuck (proxmoxve1 lxc:230 report, // v25.34.4). "Open terminal" still uses `resolve_console_target` — // there the operator wants a shell inside the guest. let (console_type, console_name) = recipe_console_target(); // Cross-node: if the finding is on a peer (scope.node_id != // this server's node_id), surface the peer's id so console.html // can use the existing remote-console proxy. `cluster.get_node` // accepts both the locally-assigned cluster key and the peer's // self_id, so passing scope.node_id (the self_id stamped by the // originating analyzer) resolves correctly on either path. let remote_node_id: Option = if p.scope.node_id != state.node_id { Some(p.scope.node_id.clone()) } else { None }; // Friendly hostname for the UI — `console_name` for `host` // targets is the literal string "host" (the resolver returns // it that way so the WS path is `/ws/console/host/host`), not // a hostname the operator would recognise. let node_hostname = resolve_node_hostname(state, &p.scope.node_id); Ok(ResolvedProposalTarget { proposal: p, console_type, console_name, remote_node_id, node_hostname }) } /// Finding types AUTOFIX may compose a runnable command for. These are /// the only proposals whose remediation `commands` are a self-contained /// package-update recipe that is safe to join and run unattended. Every /// OTHER finding type's commands can include review/inspect steps or /// state-changing actions that must be approved consciously (e.g. a /// tamper-baseline reseed, a `docker system prune`), so they are never /// eligible for the join-and-run path — the endpoint refuses them. /// Mirrors `PRED_AUTOFIX_TYPES` in web/js/app.js; the gate lives on /// BOTH sides so a direct API call can't bypass the client filter. const AUTOFIX_FINDING_TYPES: [&str; 2] = [ crate::predictive::vulnerability::FINDING_TYPE, // host_security_updates_pending crate::predictive::osv::FINDING_TYPE, // osv_vulnerability_detected ]; /// Build the single shell command AUTOFIX runs for a proposal. /// /// PRECONDITION: only called for a finding type in /// [`AUTOFIX_FINDING_TYPES`], whose analyzers emit plain single-line /// commands. The comment filter below drops any `#`-prefixed ENTRY /// wholesale, which is correct for those inputs (the only comment line /// they emit is the OSV "ecosystem not recognised" placeholder, a pure /// comment with nothing to run). It must not be handed a multi-line /// entry that packs a comment and a real command into one string. /// /// The analyzer's remediation `commands` are an ORDERED RECIPE, not a /// menu — e.g. apt security updates emit `[apt-get update, apt-get -s /// upgrade | grep -i security, apt-get upgrade -y]`: refresh the index, /// preview, then apply. Running only `commands[0]` (as the old autofix /// did) therefore just refreshed the package index and never upgraded /// anything — the exact bug operators hit. /// /// So join every runnable line into one sequential script and export /// `DEBIAN_FRONTEND=noninteractive` up front so an unattended apt run /// never blocks on a conffile / service-restart prompt (harmless on /// non-apt hosts). Sequenced with `;` not `&&` because an intermediate /// diagnostic line (the `apt-get -s upgrade | grep …` preview) exits /// non-zero when it finds nothing and must not abort the apply. /// /// Returns `None` when the recipe is comment-only (e.g. the OSV /// "ecosystem not recognised" placeholder) — nothing to run. fn compose_autofix_command(commands: &[String]) -> Option { let runnable: Vec<&str> = commands .iter() .map(|c| c.trim()) .inspect(|c| { // Tripwire for the single-line PRECONDITION above: the // `starts_with('#')` filter drops a comment ENTRY wholesale, // which silently loses a real command if some future // eligible analyzer ever packs `"# note\n"` into one // entry (as tamper_detection does — currently not eligible). // Fail loudly in debug/test builds if that day comes. debug_assert!(!c.contains('\n'), "autofix recipe entry has an embedded newline: {c:?}"); }) .filter(|c| !c.is_empty() && !c.starts_with('#')) .collect(); if runnable.is_empty() { return None; } Some(format!( "export DEBIAN_FRONTEND=noninteractive ; {}", runnable.join(" ; ") )) } /// GET /api/proposals/{id}/autofix-command — return the SINGLE composed /// command AUTOFIX runs, plus the resolved console target. Unlike /// `/command/{idx}` (which returns one line of the recipe verbatim), /// this joins the analyzer's whole remediation recipe into one /// sequential non-interactive script so the actual upgrade step runs. /// Auth-gated; the command is composed from the analyzer's on-disk /// proposal store, never from user input. pub async fn predictive_proposal_autofix_command( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let t = match resolve_proposal_target(&id, &state).await { Ok(t) => t, Err(resp) => return resp, }; // SECURITY (A01): the join-and-run path is only valid for the // package-update finding types. Refuse everything else server-side // so a hand-crafted request can't get a runnable script composed for // a proposal whose commands include review/inspect or state-changing // steps. The client applies the same allow-list, but the client is // not the trust boundary. if !AUTOFIX_FINDING_TYPES.contains(&t.proposal.finding_type.as_str()) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "this finding type is not eligible for autofix", })); } let cmds = match &t.proposal.remediation { crate::predictive::RemediationPlan::Manual { commands, .. } => commands, _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "proposal has no Manual remediation commands", })), }; let Some(command) = compose_autofix_command(cmds) else { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "proposal has no runnable autofix command", })); }; HttpResponse::Ok().json(serde_json::json!({ "command": command, "console_type": t.console_type, "console_name": t.console_name, "remote_node_id": t.remote_node_id, "node_hostname": t.node_hostname, "title": t.proposal.title, })) } /// Resolve a proposal's `scope.node_id` to a human-readable hostname /// for status displays. Tries the cluster's node table first, then /// falls back to the local node's own hostname when the id matches /// `state.node_id` (covers the case where this node hasn't been /// surfaced via `get_node` yet — e.g. very early in startup). /// Returns `node_id` verbatim only as a last resort. fn resolve_node_hostname(state: &web::Data, node_id: &str) -> String { if let Some(n) = state.cluster.get_node(node_id) && !n.hostname.is_empty() { return n.hostname; } if node_id == state.node_id && let Some(n) = state.cluster.get_all_nodes().into_iter().find(|n| n.is_self) && !n.hostname.is_empty() { return n.hostname; } node_id.to_string() } /// GET /api/proposals/{id}/console-target — return just the /// `(console_type, console_name, remote_node_id, title)` for a /// proposal, without requiring it to have a Manual remediation /// command list. Used by the Inbox's "Open terminal" button: the /// operator wants an interactive shell on the proposal's target /// (host / docker exec / lxc-attach / vm serial) so they can poke /// around manually instead of running the suggested command. This /// deliberately differs from `predictive_proposal_command`: commands /// run in the host shell (recipes are written for it), while this /// opens a shell on the resource itself via `resolve_console_target`. pub async fn predictive_proposal_console_target( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let local_p: Option = { let store = state.predictive_proposals.read() .unwrap_or_else(|e| e.into_inner()); store.get(&id).cloned() }; let p = match local_p { Some(p) => p, None => match fetch_proposal_from_peers(&id, &state).await { Some(p) => p, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found", })), }, }; let (console_type, console_name) = resolve_console_target(&p); let remote_node_id: Option = if p.scope.node_id != state.node_id { Some(p.scope.node_id.clone()) } else { None }; let node_hostname = resolve_node_hostname(&state, &p.scope.node_id); HttpResponse::Ok().json(serde_json::json!({ "console_type": console_type, "console_name": console_name, "remote_node_id": remote_node_id, "node_hostname": node_hostname, "title": p.title, })) } /// GET /api/proposals/{id}/history — return the metric history /// (rolling samples + projected ETA) backing a trend-based proposal, /// so the inbox can render an inline sparkline next to the textual /// "fills in ~5 h" estimate. /// /// Today only the three disk-fill variants have populated history /// (host filesystems via `disk_fill::METRIC`, Docker + LXC container /// storage via `container_disk::METRIC` — both use the proposal's /// `scope.resource_id` as the history key, by happy convention). For /// any other finding type we return an empty samples array; the /// frontend then just omits the graph rather than erroring. /// /// Peer-owned proposals fall back to the cluster fan-out — same /// pattern as `predictive_proposal_command` — so the operator sees a /// graph even when the proposal lives on a peer in this cluster. pub async fn predictive_proposal_history( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let local_p: Option = { let store = state.predictive_proposals.read() .unwrap_or_else(|e| e.into_inner()); store.get(&id).cloned() }; // If the proposal isn't in the local store, forward the GET to // peers using the cluster secret. Each peer runs the same handler // against its OWN MetricsHistory, which is where the samples for // that peer's resources live. let p = match local_p { Some(p) => p, None => { // Cycle-breaker: if this GET itself arrived from a peer it // must not re-fan-out (see `is_inter_node_forward`) — that // recursion is the same fleet-wide storm as the POST actions. // Return 404 (NOT a 200 "empty history") so the origin's // `forward_proposal_get_to_peers` treats us as "not the // owner, try the next peer" and still finds the node that // actually holds the proposal + its history samples. if is_inter_node_forward(&caller) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on this node", })); } return forward_proposal_get_to_peers(&state, &id, "history", is_operator_request(&caller)).await; } }; // Map (finding_type, scope) → (history_key, metric_name). Only // the trend-based analyzers have populated history; for others we // return an empty samples array. let (history_key, metric, target_pct): (&str, &str, f64) = match p.finding_type.as_str() { "disk_fill_eta" => { let key = p.scope.resource_id.as_deref().unwrap_or(""); (key, crate::predictive::disk_fill::METRIC, crate::predictive::disk_verdict::FILL_TARGET_PCT) } "docker_storage_fill_eta" | "lxc_storage_fill_eta" => { // container_disk records under the same resource_id // form ("docker:foo" / "lxc:foo") that the analyzer // stamps onto scope.resource_id. let key = p.scope.resource_id.as_deref().unwrap_or(""); (key, crate::predictive::container_disk::METRIC, crate::predictive::disk_verdict::FILL_TARGET_PCT) } _ => { return HttpResponse::Ok().json(serde_json::json!({ "metric": "", "unit": "", "samples": [], "supported": false, })); } }; if history_key.is_empty() { return HttpResponse::Ok().json(serde_json::json!({ "metric": metric, "unit": "%", "samples": [], "supported": false, })); } let metrics = state.predictive_metrics.read() .unwrap_or_else(|e| e.into_inner()).clone(); let samples_vec: Vec = match metrics.samples(history_key, metric) { Some(deque) => deque.iter().map(|s| serde_json::json!({ "ts": s.ts.to_rfc3339(), "value": s.value, })).collect(), None => Vec::new(), }; // Compute the live verdict so the frontend doesn't have to // re-implement linear_fit. Falls back to None when the series // is too short / flat / shrinking (same gates as the analyzer). let (current, slope_per_hour, eta_hours) = if let Some(deque) = metrics.samples(history_key, metric) { let cur = deque.back().map(|s| s.value).unwrap_or(0.0); let v = crate::predictive::disk_verdict::compute_verdict(deque, cur, target_pct); let slope = v.as_ref().map(|x| x.slope_pct_per_hour).unwrap_or(0.0); let eta = v.as_ref().and_then(|x| x.eta_hours); (cur, slope, eta) } else { (0.0, 0.0, None) }; HttpResponse::Ok().json(serde_json::json!({ "metric": metric, "unit": "%", "supported": true, "samples": samples_vec, "current": current, "slope_per_hour": slope_per_hour, "fill_target_pct": target_pct, "eta_hours": eta_hours, })) } /// GET-equivalent fan-out for `/api/proposals/{id}/{action}`. Tries /// every online wolfstack peer in the local cluster first /// (X-WolfStack-Secret auth), then every federated cluster /// (Bearer wsk_… auth via `federation::fetch_json`). Returns the /// first 2xx response. /// /// `include_federations` gates the cross-cluster hop — see the POST /// twin `forward_proposal_action_to_peers`. A relayed GET passes /// `false` so it never re-federates. async fn forward_proposal_get_to_peers( state: &web::Data, proposal_id: &str, action: &str, include_federations: bool, ) -> HttpResponse { let path = format!("/api/proposals/{}/{}", urlencoding::encode(proposal_id), urlencoding::encode(action)); // ─── Local-cluster peers ─── let peers: Vec<_> = state.cluster.get_all_nodes().into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack" && n.online) .collect(); let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; for peer in &peers { for url in build_node_urls(&peer.address, peer.port, &path) { let res = client.get(&url) .timeout(std::time::Duration::from_secs(8)) .peer_auth(&secret) .send().await; let Ok(resp) = res else { continue; }; if resp.status().is_success() { if let Ok(v) = resp.json::().await { return HttpResponse::Ok().json(v); } } else { let _ = resp.bytes().await; } } } // ─── Federated clusters ─── // Each federation is a separate cluster reached via Bearer auth. // Its own handler fans out to its OWN local peers on a miss, so one // hop per federation reaches every node it owns. We only take this // hop for operator-originated requests; a relayed GET passes // include_federations=false so a federation entry node never // re-federates (anti-loop — see `is_operator_request`). let federations: Vec = if include_federations { let s = state.federations.read().unwrap_or_else(|e| e.into_inner()); s.clusters.clone() } else { Vec::new() }; for fc in federations { if let Ok(v) = crate::federation::fetch_json(&fc, &path).await { return HttpResponse::Ok().json(v); } } HttpResponse::NotFound().json(serde_json::json!({ "error": "proposal not found on any reachable cluster peer or federated cluster" })) } /// Look for a proposal on every online wolfstack peer. Returns the /// first 200 response. Used as a fallback in `predictive_proposal_command` /// when the proposal id isn't in this node's local store — i.e. the /// finding lives on a peer and the operator clicked Run from the /// aggregated cluster Inbox. async fn fetch_proposal_from_peers( id: &str, state: &web::Data, ) -> Option { let peers: Vec<_> = state.cluster.get_all_nodes() .into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack" && n.online) .collect(); if peers.is_empty() { return None; } let secret = state.cluster_secret.clone(); let client = &*API_HTTP_CLIENT; let path = format!("/api/proposals/{}", urlencoding::encode(id)); for peer in peers { for url in build_node_urls(&peer.address, peer.port, &path) { let res = client.get(&url) .timeout(std::time::Duration::from_secs(5)) .peer_auth(&secret) .send() .await; let Ok(resp) = res else { continue }; if !resp.status().is_success() { let _ = resp.bytes().await; continue; } if let Ok(p) = resp.json::().await { return Some(p); } } } None } /// Console target for running a proposal's remediation commands: always /// the host shell, because every analyzer writes its recipe to be pasted /// on the host (see the call site in `resolve_proposal_target`). fn recipe_console_target() -> (String, String) { ("host".into(), "host".into()) } /// Console target for "Open terminal" — a shell on the finding's /// resource itself. Map a proposal's `scope.resource_id` to a /// `(console_type, console_name)` pair compatible with the existing `/ws/console/ /// {type}/{name}` route + `console.html?type=...&name=...` URL. /// Conventions match what each analyzer writes into resource_id. fn resolve_console_target(p: &crate::predictive::Proposal) -> (String, String) { console_target_for_resource(p.scope.resource_id.as_deref().unwrap_or("")) } /// The `resource_id` → console mapping behind `resolve_console_target`, /// split out so it is unit-testable without building a `Proposal`. fn console_target_for_resource(rid: &str) -> (String, String) { // Intrusion findings: `intrusion:|` (predictive/intrusion). // Checked first — the item after `|` is a path or key, never part of a // container name. Proxmox CTs are addressed by vmid, the same name // lxc_list_all reports for them. if let Some((target, _)) = crate::predictive::intrusion::parse_resource(rid) { if let Some(id) = target.strip_prefix("lxc:").or_else(|| target.strip_prefix("pve:")) { return ("lxc".into(), id.to_string()); } if let Some(id) = target.strip_prefix("docker:") { return ("docker".into(), id.to_string()); } return ("host".into(), "host".into()); } if let Some(name) = rid.strip_prefix("docker:") { return ("docker".into(), name.to_string()); } if let Some(name) = rid.strip_prefix("lxc:") { // container_boot scopes are `lxc:boot:` / `lxc:boot:pbs:` // (distinct ids so they can't collide with other per-LXC // findings on dedup) — the console wants the container name. let name = name.strip_prefix("boot:pbs:") .or_else(|| name.strip_prefix("boot:")) .unwrap_or(name); return ("lxc".into(), name.to_string()); } // `vm:wolfnet:` is a host-side finding (the VM's TAP and // dnsmasq live on the host) and the label is a truncated TAP name, // not a VM name — so it gets the host shell, not a serial console. if rid.starts_with("vm:wolfnet:") { return ("host".into(), "host".into()); } if let Some(rest) = rid.strip_prefix("vm:") { // vm scope is `vm::` — take the name only. let name = rest.split(':').next().unwrap_or(rest); return ("vm".into(), name.to_string()); } // host shell for everything else: filesystem mounts (`/var/log`), // certs (`letsencrypt:...`, `wolfstack-tls:...`), backup // schedules (`backup:`), node-level findings (`host`, // `sshd`), and per-unit findings (`my-unit.service`). ("host".into(), "host".into()) } /// POST /api/proposals/run-now — synchronously run one orchestrator /// tick instead of waiting for the next 5-min cadence. Useful right /// after the operator clears a finding to refresh the inbox. pub async fn predictive_proposals_run_now( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let proposals = state.predictive_proposals.clone(); let acks = state.predictive_acks.clone(); let metrics = state.predictive_metrics.clone(); let monitor = state.monitor.clone(); let node_id = state.node_id.clone(); crate::predictive::orchestrator::tick(&proposals, &acks, &metrics, &monitor, &node_id).await; invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } // ─── Acks (operator suppressions) ───────────────────────────────── pub async fn predictive_acks_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let store = match state.predictive_acks.read() { Ok(g) => g, Err(e) => e.into_inner(), }; HttpResponse::Ok().json(&store.acks) } #[derive(Deserialize)] pub struct CreateAckRequest { pub finding_type: String, pub scope: crate::predictive::AckScope, pub reason: String, /// `None` → 180-day default. `Some(n)` clamped to 1..3650. pub lifetime_days: Option, } pub async fn predictive_acks_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let r = body.into_inner(); if r.reason.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "ack reason is required — it's what makes the \ suppression auditable later", })); } let lifetime = r.lifetime_days .map(|d| chrono::Duration::days(d.clamp(1, 3650))); let ack = crate::predictive::Ack::new( r.finding_type, r.scope, r.reason, user.clone(), lifetime, ); let id = ack.id.clone(); // Serialisation of plain strings/timestamps can't fail; if it ever // does, skip replication loudly rather than POST an empty body. let replica = match serde_json::to_vec(&ack) { Ok(b) => Some(b), Err(e) => { warn!("predictive ack {}: could not serialise for peers: {}", ack.id, e); None } }; { let mut store = match state.predictive_acks.write() { Ok(g) => g, Err(e) => e.into_inner(), }; store.add(ack); let _ = store.save(); } invalidate_cluster_cache(&state); // An ack used to live only on the node the browser was logged into. // The finding's OWN node never saw it, so opening the inbox from any // other node brought the finding straight back (JJ, 2026-09-22). Copy // it to every peer so each node's inbox and analyzer honour it. Local // cluster only, by design: the inbox aggregate is cluster-local, and a // federated cluster keeps its own acks. A request forwarded from a // peer never re-fans-out. let unreached = if is_inter_node_forward(&user) { Vec::new() } else if let Some(replica) = replica { let outcomes = fan_out_to_peers( &state, reqwest::Method::POST, "/api/proposal-acks/replica", Some(replica), ).await; outcomes.into_iter() .filter_map(|(peer, o)| match o { PeerOutcome::Ok(_) => None, PeerOutcome::NotFound => Some(format!( "{} (too old to share acknowledgements — upgrade it)", peer.hostname)), PeerOutcome::Failed(e) => Some(format!("{} ({})", peer.hostname, e)), }) .collect::>() } else { vec!["every peer (the acknowledgement could not be encoded — see the WolfStack log)".to_string()] }; if !unreached.is_empty() { warn!("predictive ack {} not copied to: {}", id, unreached.join(", ")); } HttpResponse::Ok().json(serde_json::json!({ "success": true, "id": id, "unreached": unreached, })) } /// POST /api/proposal-acks/replica — a peer copying an ack it created to /// this node (see `predictive_acks_create`). Peer-only: an operator /// creates acks through `POST /api/proposal-acks`, which owns the reason /// check and stamps who acknowledged it. pub async fn predictive_acks_replica( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; if !is_inter_node_forward(&caller) { return HttpResponse::Forbidden().json(serde_json::json!({ "error": "ack replicas are only accepted from cluster peers", })); } let ack = body.into_inner(); if ack.reason.trim().is_empty() || ack.id.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "ack replica is missing its id or reason", })); } { let mut store = match state.predictive_acks.write() { Ok(g) => g, Err(e) => e.into_inner(), }; store.upsert_replica(ack); let _ = store.save(); } invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } /// DELETE /api/proposal-acks/{id} — revoke an ack. From an operator this /// removes it on this node AND every peer (acks are copied cluster-wide, /// and ones made before that only exist on the node they were made on); /// from a peer it removes the local copy only. pub async fn predictive_acks_remove( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(c) => c, Err(resp) => return resp, }; let id = path.into_inner(); let removed_here = { let mut store = match state.predictive_acks.write() { Ok(g) => g, Err(e) => e.into_inner(), }; let removed = store.remove(&id); if removed { let _ = store.save(); } removed }; if removed_here { invalidate_cluster_cache(&state); } if is_inter_node_forward(&caller) { return if removed_here { HttpResponse::Ok().json(serde_json::json!({ "success": true })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "ack not found" })) }; } let path = format!("/api/proposal-acks/{}", urlencoding::encode(&id)); let outcomes = fan_out_to_peers(&state, reqwest::Method::DELETE, &path, None).await; let mut removed_on_peers = 0usize; let mut unreached = Vec::new(); for (peer, o) in outcomes { match o { PeerOutcome::Ok(_) => removed_on_peers += 1, PeerOutcome::NotFound => {} PeerOutcome::Failed(e) => unreached.push(format!("{} ({})", peer.hostname, e)), } } if !removed_here && removed_on_peers == 0 { if !unreached.is_empty() { // Not found anywhere we could reach — but a node that could hold // it didn't answer, so "not found" would be a lie. return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!( "acknowledgement not found on any reachable node; could not reach {}", unreached.join(", "), ), })); } return HttpResponse::NotFound().json(serde_json::json!({ "error": "ack not found" })); } if !unreached.is_empty() { warn!("predictive ack {} revoke did not reach: {}", id, unreached.join(", ")); } HttpResponse::Ok().json(serde_json::json!({ "success": true, "unreached": unreached })) } /// Result of one peer call in `fan_out_to_peers`. enum PeerOutcome { /// 2xx; the JSON body, or `Null` when the body wasn't JSON. Ok(serde_json::Value), /// HTTP 404 — the peer doesn't hold the thing, or predates the endpoint. NotFound, /// Unreachable, timed out, or any other status. Short, operator-readable. Failed(String), } /// Send one request to every WolfStack peer in this cluster, concurrently, /// authenticated with the cluster secret. Each peer's candidate URLs /// (`build_node_urls`) are tried in order until one answers. Returns /// `(peer, outcome)` per peer. Peers the cluster already knows are offline /// aren't called but ARE returned (`Failed("offline")`), so a caller can /// tell the operator which nodes an ack or revoke never reached. async fn fan_out_to_peers( state: &web::Data, method: reqwest::Method, path: &str, body: Option>, ) -> Vec<(crate::agent::Node, PeerOutcome)> { let peers: Vec<_> = state.cluster.get_all_nodes().into_iter() .filter(|n| !n.is_self && n.node_type == "wolfstack") .collect(); let secret = state.cluster_secret.clone(); let calls = peers.into_iter().map(|peer| { let urls = build_node_urls(&peer.address, peer.port, path); let method = method.clone(); let body = body.clone(); let secret = secret.clone(); async move { if !peer.online { return (peer, PeerOutcome::Failed("offline".to_string())); } let mut outcome = PeerOutcome::Failed("unreachable".to_string()); for url in urls { let mut rb = API_HTTP_CLIENT.request(method.clone(), &url) .timeout(std::time::Duration::from_secs(10)) .peer_auth(&secret); if let Some(b) = &body { rb = rb.header("content-type", "application/json").body(b.clone()); } let resp = match rb.send().await { Ok(r) => r, Err(e) if e.is_timeout() => { outcome = PeerOutcome::Failed("timed out".to_string()); continue; } Err(_) => continue, }; let status = resp.status(); outcome = if status.is_success() { PeerOutcome::Ok(resp.json::().await .unwrap_or(serde_json::Value::Null)) } else if status == reqwest::StatusCode::NOT_FOUND { let _ = resp.bytes().await; PeerOutcome::NotFound } else { let _ = resp.bytes().await; PeerOutcome::Failed(format!("HTTP {}", status.as_u16())) }; break; } (peer, outcome) } }); futures::future::join_all(calls).await } /// GET /api/proposals/suppressed — what this node is keeping out of its /// inbox on the operator's say-so: dismissed findings and active acks. /// Snoozed findings aren't listed; they stay in the inbox with a /// SNOOZED badge and their own Unsnooze button. pub async fn predictive_proposals_suppressed( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(local_suppressed(&state)) } #[derive(Serialize, Deserialize, Default)] struct SuppressedSet { dismissed: Vec, acks: Vec, } fn local_suppressed(state: &web::Data) -> SuppressedSet { let now = chrono::Utc::now(); let dismissed = { let store = state.predictive_proposals.read().unwrap_or_else(|e| e.into_inner()); store.proposals.iter() .filter(|p| matches!(p.status, crate::predictive::proposal::ProposalStatus::Dismissed { .. })) .cloned() .collect() }; let acks = { let store = state.predictive_acks.read().unwrap_or_else(|e| e.into_inner()); store.acks.iter().filter(|a| a.is_active(now)).cloned().collect() }; SuppressedSet { dismissed, acks } } /// An active ack plus the hostnames of the nodes holding a copy, so the /// operator can see one that didn't reach a node and revoke or redo it. #[derive(Serialize)] struct HeldAck { #[serde(flatten)] ack: crate::predictive::Ack, held_on: Vec, } /// GET /api/proposals/suppressed/cluster — `suppressed` from this node and /// every peer, for the inbox's Suppressed view. Dismissals live on the /// finding's own node so they concatenate; acks are copied cluster-wide /// so they're merged by id. Unreachable peers are listed in `nodes` like /// the inbox aggregate, never dropped silently. pub async fn predictive_proposals_suppressed_cluster( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } use crate::predictive::cluster::NodeAggregateStatus; let nodes_snapshot = state.cluster.get_all_nodes(); let self_node = nodes_snapshot.iter().find(|n| n.is_self).cloned(); let self_host = self_node.as_ref().map(|n| n.hostname.clone()).unwrap_or_default(); let mut nodes = vec![NodeAggregateStatus { node_id: state.node_id.clone(), hostname: self_host.clone(), is_self: true, responded: true, error: None, cluster_name: self_node.as_ref().map(resolve_cluster_label).unwrap_or_default(), }]; let mut sets = vec![(self_host, local_suppressed(&state))]; for (peer, outcome) in fan_out_to_peers( &state, reqwest::Method::GET, "/api/proposals/suppressed", None, ).await { // Same canonical id the peer stamps on its proposals' scopes. let node_id = peer.self_id.clone().unwrap_or_else(|| peer.id.clone()); let cluster_name = resolve_cluster_label(&peer); let host = peer.hostname; let error = match outcome { PeerOutcome::Ok(v) => match serde_json::from_value::(v) { Ok(set) => { sets.push((host.clone(), set)); None } Err(e) => Some(format!("invalid response shape: {}", e)), }, PeerOutcome::NotFound => Some("too old to list suppressions — upgrade it".to_string()), PeerOutcome::Failed(e) => Some(e), }; nodes.push(NodeAggregateStatus { node_id, hostname: host, is_self: false, responded: error.is_none(), error, cluster_name, }); } let mut dismissed = Vec::new(); let mut acks: Vec = Vec::new(); for (host, set) in sets { dismissed.extend(set.dismissed); for ack in set.acks { match acks.iter_mut().find(|h| h.ack.id == ack.id) { Some(h) => h.held_on.push(host.clone()), None => acks.push(HeldAck { ack, held_on: vec![host.clone()] }), } } } dismissed.sort_by_key(|p| std::cmp::Reverse(p.updated_at)); acks.sort_by_key(|h| std::cmp::Reverse(h.ack.created_at)); HttpResponse::Ok().json(serde_json::json!({ "dismissed": dismissed, "acks": acks, "nodes": nodes, })) } // ─── Tamper-detection baselines ─────────────────────────────────── /// POST /api/predictive/baselines/reseed/{slug} — operator hook to /// re-anchor a tamper-detection baseline after an intentional change /// to a security-critical file. Without this, the next tick would /// auto-revert the operator's legitimate edit. /// /// Slug shape: `` with leading slash stripped and `/` → `__`. /// E.g. `etc__ssh__sshd_config` for `/etc/ssh/sshd_config`. The /// operator usually doesn't type slugs by hand — they Run or Copy the /// pre-filled reseed command from the proposal card's remediation, which /// already carries the correct slug (and authenticates with the node's /// cluster secret). /// /// Body: optional `{ "reason": "..." }`. Reason is appended to the /// baseline metadata so the audit trail records WHY the reseed /// happened and WHO triggered it. #[derive(serde::Deserialize, Default)] pub struct ReseedBaselineBody { #[serde(default)] pub reason: String, } /// Admin gate for the tamper-protection controls: these accept changes to /// /etc/passwd, sudoers and root's SSH keys, so only a signed-in admin — /// never an API key or a peer's cluster secret. fn tamper_admin(req: &HttpRequest, state: &web::Data) -> Result { let caller = require_auth(req, state)?; if caller.starts_with("apikey:") || caller == "cluster-node" { return Err(HttpResponse::Forbidden().json(serde_json::json!({ "error": "Only a signed-in administrator can change tamper protection." }))); } require_admin(&caller)?; Ok(caller) } /// GET /api/security/tamper-protection — is tamper protection paused? pub async fn tamper_protection_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(r) = require_auth(&req, &state) { return r; } match web::block(crate::predictive::tamper_detection::pause_state).await { Ok(s) => HttpResponse::Ok().json(s), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(serde::Deserialize)] pub struct TamperProtectionBody { pub paused: bool, } /// POST /api/security/tamper-protection {paused} — pause for maintenance, /// or resume (which accepts every protected file as it is now). pub async fn tamper_protection_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match tamper_admin(&req, &state) { Ok(c) => c, Err(r) => return r }; let pause = body.paused; let by = caller.clone(); let result = web::block(move || { use crate::predictive::tamper_detection as td; if pause { td::pause(&by).map(|s| serde_json::json!({ "paused": true, "state": s })) } else { td::resume(&by).map(|accepted| serde_json::json!({ "paused": false, "accepted": accepted })) } }).await; match result { Ok(Ok(v)) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(v) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(serde::Deserialize)] pub struct TamperFindingBody { pub finding_type: String, } /// POST /api/security/tamper/accept {finding_type} — the operator made the /// change on an Inbox tamper card: its changed files become the baseline. pub async fn tamper_finding_accept( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match tamper_admin(&req, &state) { Ok(c) => c, Err(r) => return r }; let ft = body.finding_type.clone(); match web::block(move || crate::predictive::tamper_detection::accept_finding(&ft, &caller)).await { Ok(Ok(paths)) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "accepted": paths })) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } /// POST /api/security/tamper/revert {finding_type} — put an Inbox tamper /// card's changed files back to their baseline. pub async fn tamper_finding_revert( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { let caller = match tamper_admin(&req, &state) { Ok(c) => c, Err(r) => return r }; let ft = body.finding_type.clone(); match web::block(move || crate::predictive::tamper_detection::revert_finding(&ft, &caller)).await { Ok(Ok(paths)) => { invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "reverted": paths })) } Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } pub async fn predictive_baselines_reseed( req: HttpRequest, state: web::Data, path: web::Path, body: Option>, ) -> HttpResponse { let user = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp, }; let slug = path.into_inner(); // Slug → absolute path. Reject anything that doesn't look like a // baselined system file — defensive against directory-traversal. if slug.contains("..") || slug.starts_with('/') || slug.contains('\0') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "invalid slug — must be the slug form `etc__ssh__sshd_config`" })); } let file_path = format!("/{}", slug.replace("__", "/")); let reason = body.map(|b| b.into_inner().reason).unwrap_or_default(); match crate::predictive::baselines::reseed(&file_path, &user, &reason) { Ok(b) => HttpResponse::Ok().json(serde_json::json!({ "success": true, "path": b.path, "sha256": b.sha256, "seeded_at": b.seeded_at, "seeded_by": b.seeded_by, })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("reseed {} failed: {}", file_path, e) })), } } // ─── Threat-intel safety switch (per-cluster, off by default) ────── // // v23.2.2: enforcement is per-cluster (Off / DryRun / Enforce), default // Off everywhere. The legacy /enable + /disable endpoints are kept as // backward-compatible shortcuts that operate on the receiving node's // own cluster, but /enable now sets DryRun (never Enforce) — promotion // to Enforce goes through the explicit /state endpoint with a fresh // preflight gate. use crate::predictive::threat_intel as ti; pub async fn predictive_threat_intel_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // status_snapshot() runs `which`, `iptables -C`, `ipset list`, // and parses the local feed file — all blocking. Defer to a // blocking worker so we don't stall the Tokio reactor. match tokio::task::spawn_blocking(ti::status_snapshot).await { Ok(s) => HttpResponse::Ok().json(s), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("status task: {}", e), })), } } /// POST /api/threat-intel/test-feed — operator-clickable diagnostic /// that HEADs the upstream FireHOL feed URL with a short timeout and /// reports DNS/TCP/TLS/HTTP failure layer. Surfaces *why* a node's /// threat-intel isn't working when the analyzer can't fetch the feed: /// "Could not resolve host" → DNS misconfig; "Connection refused" → /// firewall; "SSL certificate problem" → time/cert issue. Without /// this endpoint operators had no way to tell which layer broke. pub async fn threat_intel_test_feed( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match tokio::task::spawn_blocking(ti::test_feed_blocking).await { Ok(r) => HttpResponse::Ok().json(r), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("test-feed task: {}", e), })), } } /// GET /api/threat-intel/fleet-status — aggregates every cluster peer's /// `/api/predictive/threat-intel/status` into one envelope so the Fleet /// Security page can render a per-node table. Same shape as /// `/api/fleet/security/lockouts`: `{ nodes: [{ hostname, address, /// status, data, error }] }`. Klas's exact ask — "a node that doesn't /// want to work with threat intel and i can't find the place where i /// can check why and fix it" — landed here as the spot-check view: one /// glance and the misbehaving node is visible (feed entries = 0, /// missing rules, stale feed, etc). pub async fn threat_intel_fleet_status( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // `status_snapshot` is blocking (runs `which`, `iptables -C`, // `ipset list`, and parses the feed file on disk). Compute it on // the blocking pool BEFORE entering the fanout so the local // closure inside `fleet_fanout_get` is a trivial move that // doesn't stall the async reactor — the fanout still does its // own per-peer 8s timeouts for remote calls. let local_snapshot = tokio::task::spawn_blocking(ti::status_snapshot) .await .unwrap_or_else(|_| ti::ThreatIntelStatus { enabled: false, state: ti::EnforceState::Off, cluster: ti::this_node_cluster(), ipset_available: false, iptables_rules_present: false, feed_entry_count: 0, ipset_entry_count: 0, feed_age_secs: None, migration_completed: false, }); let nodes = fleet_fanout_get::( &state, "/api/predictive/threat-intel/status", move || local_snapshot, ).await; HttpResponse::Ok().json(serde_json::json!({ "nodes": nodes })) } /// Legacy enable shortcut — now equivalent to "set this node's /// cluster to DryRun". Will never install iptables rules on its own; /// the operator must explicitly Promote afterwards. pub async fn predictive_threat_intel_enable( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = ti::this_node_cluster(); let new_state = match ti::set_cluster_state(&cluster, ti::EnforceState::DryRun) { Ok(s) => s, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; propagate_threat_intel_state(&state, &new_state); HttpResponse::Ok().json(serde_json::json!({ "success": true, "cluster": cluster, "state": "dry-run", "note": "Cluster set to DryRun. The next predictive tick will fetch the feed and compute a preflight, but no traffic will be blocked. Promote to Enforce from the Predictive Inbox after reviewing the preflight.", })) } /// Disable shortcut — sets this node's cluster to Off and tears /// down any kernel state immediately. Same instant-safety contract /// the v23.2.1 disable button had. pub async fn predictive_threat_intel_disable( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = ti::this_node_cluster(); let new_state = match ti::set_cluster_state(&cluster, ti::EnforceState::Off) { Ok(s) => s, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; propagate_threat_intel_state(&state, &new_state); HttpResponse::Ok().json(serde_json::json!({ "success": true, "cluster": cluster, "state": "off", "note": "Cluster set to Off — iptables DROP rules removed, ipset destroyed, peers notified. Traffic should flow normally.", })) } #[derive(Debug, Deserialize)] pub struct ThreatIntelStateRequest { /// Cluster to change. Required. pub cluster: String, /// New state: "off" | "dry-run" | "enforce". pub state: String, /// Anti-fat-finger: when promoting to Enforce the operator must /// re-type the cluster name. Ignored for Off / DryRun. #[serde(default)] pub confirm_cluster_name: Option, /// Stateless freshness gate: when promoting to Enforce, the /// frontend must include the `generated_at` epoch-seconds of the /// preflight report the operator just reviewed (max across all /// per-node reports). Ignored for Off / DryRun. #[serde(default)] pub preflight_generated_at: u64, } /// POST /api/predictive/threat-intel/state — explicit cluster state /// change. The only path that can reach Enforce. pub async fn predictive_threat_intel_set_state( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = body.cluster.trim().to_string(); if cluster.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "cluster name is required", })); } let target = match ti::EnforceState::from_str_opt(&body.state) { Some(s) => s, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("unknown state '{}'; expected one of: off, dry-run, enforce", body.state), })), }; // Promote-to-Enforce gate: typed confirmation + fresh preflight. if target == ti::EnforceState::Enforce { match body.confirm_cluster_name.as_deref().map(str::trim) { Some(name) if name == cluster => {} _ => return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("confirm_cluster_name must equal '{}' to promote to Enforce", cluster), })), } if let Err(e) = ti::require_fresh_preflight(&cluster, body.preflight_generated_at) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } } let new_state = match ti::set_cluster_state(&cluster, target) { Ok(s) => s, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), }; propagate_threat_intel_state(&state, &new_state); HttpResponse::Ok().json(serde_json::json!({ "success": true, "cluster": cluster, "state": target.as_str(), })) } /// POST /api/predictive/threat-intel/preflight — compute a dry-run /// preflight report on THIS node. Caller may fan out to other nodes /// in the cluster via the node-proxy and aggregate results. Stamps /// the preflight timestamp for this node's cluster so the promote /// gate has a fresh marker (the aggregator endpoint also stamps, /// for the cluster-wide case). pub async fn predictive_threat_intel_preflight( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let node_id = state.cluster.self_id.clone(); let report = match tokio::task::spawn_blocking(move || ti::preflight_blocking(node_id)).await { Ok(r) => r, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("preflight task: {}", e), })), }; HttpResponse::Ok().json(report) } /// POST /api/predictive/threat-intel/peer-state-push — inter-node /// endpoint authenticated by X-WolfStack-Secret. Receives a state /// file pushed from a peer and applies it locally. Idempotent. pub async fn predictive_threat_intel_peer_state_push( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } match ti::apply_peer_state(body.into_inner()) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "success": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Best-effort fan-out of an updated cluster-state file to every /// peer in *this node's* cluster. Failures are logged but never /// surface to the operator — peers that are offline will catch up /// on the next gossip cycle. fn propagate_threat_intel_state(state: &web::Data, payload: &ti::ClusterStateFile) { let payload = payload.clone(); let cluster_handle = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { let self_cluster = cluster_handle.get_self_cluster_name(); let self_id = cluster_handle.self_id.clone(); let peers: Vec<(String, String, u16)> = cluster_handle.get_all_nodes() .into_iter() .filter(|n| n.id != self_id) .filter(|n| n.cluster_name.as_deref() == Some(self_cluster.as_str())) .map(|n| (n.hostname.clone(), n.address.clone(), n.port)) .collect(); if peers.is_empty() { return; } let client = &*API_HTTP_CLIENT; for (hostname, address, port) in &peers { let urls = build_node_urls(address, *port, "/api/predictive/threat-intel/peer-state-push"); let mut delivered = false; let mut last_status: Option = None; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&secret) .json(&payload) .send() .await { Ok(resp) if resp.status().is_success() => { let _ = resp.bytes().await; tracing::info!("threat_intel: state propagated to peer '{}' ({})", hostname, address); delivered = true; break; } Ok(resp) => { // Non-success on this URL — record the // status and try the next URL (HTTPS may be // misconfigured but the HTTP fallback could // succeed). last_status = Some(resp.status().as_u16()); let _ = resp.bytes().await; continue; } Err(_) => continue, } } if !delivered { match last_status { Some(st) => tracing::warn!("threat_intel: state push to peer '{}' ({}) returned HTTP {} on every attempted URL", hostname, address, st), None => tracing::warn!("threat_intel: could not reach peer '{}' ({}) for state propagation", hostname, address), } } } }); } // ─── OSV scanner config ─────────────────────────────────────────── /// GET /api/predictive/osv-config — return the current OSV scanner /// configuration: enabled flag, OSV/KEV endpoints, kev_only mode, and /// any per-distro ecosystem overrides. pub async fn predictive_osv_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let _ = state; // config lives on disk, not in AppState let cfg = crate::predictive::osv::OsvConfig::load(); HttpResponse::Ok().json(cfg) } /// PUT /api/predictive/osv-config — replace the on-disk config. Body /// is the same `OsvConfig` shape the GET returns. Validation is /// minimal: an empty endpoint string is rejected because OSV would /// resolve `/v1/querybatch` against the empty origin, which fails /// silently rather than surfacing an obvious config mistake. pub async fn predictive_osv_config_put( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = body.into_inner(); if cfg.endpoint.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "OSV endpoint cannot be empty — leave default \ (https://api.osv.dev) or specify a self-hosted mirror", })); } if cfg.kev_endpoint.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "KEV endpoint cannot be empty — leave default \ (CISA's KEV feed) or specify a mirror URL", })); } if let Err(e) = cfg.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("failed to persist OSV config: {}", e), })); } invalidate_cluster_cache(&state); HttpResponse::Ok().json(serde_json::json!({ "success": true })) } // ─── WhatsApp webhook (inbound via Twilio) ─── /// POST /api/whatsapp/webhook — Twilio delivers inbound WhatsApp /// messages here as `application/x-www-form-urlencoded` form data. /// /// This endpoint is reachable without a session cookie because Twilio /// doesn't hold one — instead we validate the `X-Twilio-Signature` /// header (HMAC-SHA1 of URL+sorted-params signed with our Twilio auth /// token). Any request that fails the signature check is rejected /// with 403 without touching agents or the LLM. /// /// The reply comes back as TwiML in the response body so Twilio /// delivers it to the user synchronously — no outbound API call /// needed for the common case. // ─── Cluster filesystem proxy ─── // // These three endpoints let a WolfAgent tool on one node read, write, // or delete a file on a different cluster node. They require // X-WolfStack-Secret (inter-node auth) — a human session token is not // accepted. The wolfagents safety denylist (the same one that guards // exec_* and wolfstack_api) is applied on BOTH sides so both the // caller's node and the target node enforce the path allowlist. #[derive(Deserialize)] pub struct ClusterFileOp { pub path: String, #[serde(default)] pub content: String, #[serde(default)] pub append: bool, } pub async fn cluster_file_read( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // Only accept cluster-secret auth — user sessions MUST NOT hit this // endpoint. A logged-in user who wants cross-node file access goes // through the dashboard's own per-node browser, not through this // inter-node channel. match require_auth(&req, &state) { Ok(u) if u == "cluster-node" => {} Ok(_) => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "cluster file endpoint requires cluster-secret auth, not a user session" })), Err(resp) => return resp, } let path = body.path.trim(); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "path required"})); } if let Err(e) = crate::wolfagents::safety::validate_path(path) { return HttpResponse::Forbidden().json(serde_json::json!({"error": e})); } match std::fs::read(path) { Ok(bytes) => { let max = 1024 * 1024; let truncated = bytes.len() > max; let slice = &bytes[..max.min(bytes.len())]; HttpResponse::Ok().json(serde_json::json!({ "path": path, "content": String::from_utf8_lossy(slice), "total_bytes": bytes.len(), "truncated": truncated, })) } Err(e) => HttpResponse::NotFound().json(serde_json::json!({"error": format!("read: {}", e)})), } } pub async fn cluster_file_write( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { match require_auth(&req, &state) { Ok(u) if u == "cluster-node" => {} Ok(_) => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "cluster file endpoint requires cluster-secret auth" })), Err(resp) => return resp, } let path = body.path.trim(); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "path required"})); } if body.content.len() > 8 * 1024 * 1024 { return HttpResponse::BadRequest().json(serde_json::json!({"error": "content exceeds 8 MB"})); } if let Err(e) = crate::wolfagents::safety::validate_path(path) { return HttpResponse::Forbidden().json(serde_json::json!({"error": e})); } let res = if body.append { use std::io::Write; std::fs::OpenOptions::new().create(true).append(true).open(path) .and_then(|mut f| f.write_all(body.content.as_bytes())) } else { std::fs::write(path, body.content.as_bytes()) }; match res { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "path": path, "bytes": body.content.len(), "appended": body.append, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("write: {}", e) })), } } /// POST /api/cluster/semantic/search — cluster-secret-auth'd BM25 /// search against THIS node's agent memory / alerts / audit corpora. /// Used by WolfAgent tool `semantic_search` when the caller wants to /// search a different node. Mirrors the tool's args on the wire. #[derive(Deserialize)] pub struct ClusterSemanticQuery { pub query: String, #[serde(default)] pub limit: Option, #[serde(default)] pub sources: Option>, } pub async fn cluster_semantic_search( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { match require_auth(&req, &state) { Ok(u) if u == "cluster-node" => {} Ok(_) => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "cluster semantic-search endpoint requires cluster-secret auth, not a user session" })), Err(resp) => return resp, } let query = body.query.trim(); if query.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "query required"})); } let limit = body.limit.unwrap_or(10).clamp(1, 50) as usize; let sources: Vec<&str> = body.sources.as_ref() .map(|arr| arr.iter().map(|s| s.as_str()).collect()) .unwrap_or_else(|| vec!["memory", "audit", "alerts"]); let docs = crate::wolfagents::dispatch::collect_search_corpus(&sources); let matches = crate::wolfagents::dispatch::bm25_rank(query, &docs, limit); HttpResponse::Ok().json(serde_json::json!({ "query": query, "total_docs": docs.len(), "matches": matches, })) } pub async fn cluster_file_delete( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { match require_auth(&req, &state) { Ok(u) if u == "cluster-node" => {} Ok(_) => return HttpResponse::Forbidden().json(serde_json::json!({ "error": "cluster file endpoint requires cluster-secret auth" })), Err(resp) => return resp, } let path = body.path.trim(); if path.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "path required"})); } if let Err(e) = crate::wolfagents::safety::validate_path(path) { return HttpResponse::Forbidden().json(serde_json::json!({"error": e})); } match std::fs::remove_file(path) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({"path": path})), Err(e) => HttpResponse::NotFound().json(serde_json::json!({"error": format!("delete: {}", e)})), } } pub async fn whatsapp_webhook( req: HttpRequest, state: web::Data, body: web::Bytes, ) -> HttpResponse { let cfg = crate::alerting::AlertConfig::load(); if cfg.twilio_auth_token.is_empty() { return HttpResponse::ServiceUnavailable() .body("WhatsApp receiver not configured — set Twilio auth token in Settings → Alerting"); } // Parse x-www-form-urlencoded body. Twilio always uses this // content type for webhook calls. We parse manually rather than // pulling in the `url` crate — the format is well-defined and // we already have `urlencoding` for the per-value decode. let form_str = match std::str::from_utf8(&body) { Ok(s) => s, Err(_) => return HttpResponse::BadRequest().body("non-utf8 body"), }; let params: Vec<(String, String)> = form_str .split('&') .filter(|kv| !kv.is_empty()) .filter_map(|kv| { // `+` → space is an x-www-form-urlencoded thing that // straight %-decoding doesn't handle. Swap before decoding. let replace_plus = |s: &str| s.replace('+', " "); let (k, v) = kv.split_once('=').unwrap_or((kv, "")); let dk = urlencoding::decode(&replace_plus(k)).ok()?.into_owned(); let dv = urlencoding::decode(&replace_plus(v)).ok()?.into_owned(); Some((dk, dv)) }) .collect(); // Build the signed URL: Twilio signs the full URL it posted to // (scheme + host + path + query). Reconstruct from actix's // connection_info which respects X-Forwarded-* when a proxy is // in front of us. let path = req.uri().path(); let query = req.uri().query().map(|q| format!("?{}", q)).unwrap_or_default(); // Scope the `Ref` that connection_info() hands out so it is released // before the `.await` further down — a RefCell borrow must not span a // suspend point. let webhook_url = { let conn = req.connection_info(); format!("{}://{}{}{}", conn.scheme(), conn.host(), path, query) }; let signature = req.headers().get("X-Twilio-Signature") .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !crate::whatsapp_bot::validate_twilio_signature( &cfg.twilio_auth_token, &webhook_url, ¶ms, signature ) { tracing::warn!("whatsapp_webhook: signature validation failed — rejecting"); return HttpResponse::Forbidden().body("signature validation failed"); } // Pull the `From` and `Body` fields out of the validated params. let from = params.iter().find(|(k, _)| k == "From").map(|(_, v)| v.clone()).unwrap_or_default(); let msg_body = params.iter().find(|(k, _)| k == "Body").map(|(_, v)| v.clone()).unwrap_or_default(); if from.is_empty() || msg_body.is_empty() { return HttpResponse::Ok() .content_type("application/xml") .body(crate::whatsapp_bot::twiml_empty()); } // Route to agent. `handle_inbound` does the rate-limiting + agent // lookup + chat_with_agent call; returns None when no agent is // bound to this phone number (empty TwiML so Twilio doesn't retry). let reply = crate::whatsapp_bot::handle_inbound(&from, &msg_body, state.get_ref()).await; let twiml = match reply { Some(text) => crate::whatsapp_bot::twiml_reply(&text), None => crate::whatsapp_bot::twiml_empty(), }; HttpResponse::Ok() .content_type("application/xml") .body(twiml) } // ─── WolfAgents API ─── /// GET /api/agents — list every registered agent. pub async fn agents_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::wolfagents::load_all()) } /// GET /api/agents/{id} — one agent by id. pub async fn agents_get(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match crate::wolfagents::load(&id) { Some(a) => HttpResponse::Ok().json(a), None => HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})), } } /// POST /api/agents — create a new agent. Body: `{"name": "..."}` /// (plus optional overrides for system_prompt, model, provider, /// allowed_tools, discord). Missing fields pick up defaults from /// `wolfagents::new_default` which seeds from AiConfig. /// POST /api/agents/build — draft a WolfAgent from a natural-language /// request. The main AI chat calls this when the operator says "build /// me an agent that..." — we ask the configured LLM to translate the /// request into a concrete agent record (name, system_prompt, access /// level, target scope, tool allowlist). The response is NOT persisted /// — the frontend renders it as a preview with a Create button so the /// operator can review + edit before committing. This keeps the LLM /// from silently creating agents that the operator didn't authorise. pub async fn agents_build_proposal( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let request_text = body.get("request").and_then(|v| v.as_str()).unwrap_or("").trim(); if request_text.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "`request` field is required" })); } let ai_config = state.ai_agent.config.lock() .unwrap_or_else(|p| p.into_inner()).clone(); if !ai_config.is_configured() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "AI is not configured — set provider + key in Settings → AI Agent first" })); } // Build the tool catalogue string the LLM will pick from. let tool_lines: Vec = crate::wolfagents::tools::ToolId::ALL.iter().map(|t| { let danger = match t.danger() { crate::wolfagents::tools::Danger::Safe => "safe", crate::wolfagents::tools::Danger::Mutating => "mutating", crate::wolfagents::tools::Danger::Destructive => "destructive", }; format!("- {} ({}): {}", t.as_str(), danger, t.label()) }).collect(); let clusters: Vec = state.cluster.get_all_nodes().iter() .filter_map(|n| n.cluster_name.clone()) .collect::>() .into_iter().collect(); let system = format!( "You are a WolfStack agent designer. The operator describes the agent they \ want in natural language; you respond with a single JSON object describing \ the agent. No prose, no markdown fences, just the JSON.\n\n\ Known clusters: [{}]\n\n\ Tool catalogue (pick the MINIMUM set — unchecked tools are refused):\n{}\n\n\ Schema:\n\ {{\n\ \"name\": string (short, memorable — e.g. \"DiskWatchdog\"),\n\ \"system_prompt\": string (1-3 sentences describing the agent's role + output format),\n\ \"access_level\": \"read_only\" | \"read_write\" | \"confirm_all\" | \"trusted\",\n\ \"allowed_tools\": [\"tool_name\", ...],\n\ \"target_scope\": {{\n\ \"allowed_clusters\": [string, ...],\n\ \"allowed_container_patterns\": [string, ...],\n\ \"allowed_hosts\": [string, ...],\n\ \"allowed_paths\": [string, ...],\n\ \"allowed_api_paths\": [string, ...],\n\ \"allowed_email_recipients\": [string, ...]\n\ }}\n\ }}\n\n\ Rules:\n\ - Default access_level to read_only unless the request clearly implies mutation.\n\ - Grant send_email only when the request asks to 'report', 'email', 'notify', or 'alert'. \ Set allowed_email_recipients to the user's email if they give one, otherwise leave empty.\n\ - Use glob patterns for allowed_container_patterns (e.g. 'regions-*').\n\ - Use exact cluster names; if the request names a cluster, put it in allowed_clusters.\n\ - Never add a destructive tool unless the request clearly asks for destructive action.\n\ - Output ONLY the JSON object. No explanation, no fences.", clusters.join(", "), tool_lines.join("\n"), ); let reply = match crate::ai::simple_chat(&ai_config, &system, &[], request_text).await { Ok(r) => r, Err(e) => return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("AI call failed: {}", e) })), }; // Extract the JSON object from the reply. Models sometimes wrap it // in ```json fences despite the instruction; strip those tolerantly. let cleaned = extract_json_object(&reply); let proposal: serde_json::Value = match serde_json::from_str(&cleaned) { Ok(v) => v, Err(e) => return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("AI response was not valid JSON: {}", e), "raw_response": reply, })), }; // Validate tool names so the UI doesn't offer a proposal the // backend would later reject on create. Silently drop unknowns // rather than failing outright — the operator can edit anyway. let mut proposal = proposal; if let Some(tools) = proposal.get_mut("allowed_tools").and_then(|v| v.as_array_mut()) { tools.retain(|t| t.as_str() .and_then(crate::wolfagents::tools::ToolId::from_str) .is_some()); } HttpResponse::Ok().json(serde_json::json!({ "proposal": proposal, "raw": reply })) } /// Best-effort extraction of a JSON object from an LLM response that /// might be wrapped in ```json fences or trailing prose. Returns the /// substring from the first `{` to the last `}`. fn extract_json_object(s: &str) -> String { let start = s.find('{'); let end = s.rfind('}'); match (start, end) { (Some(a), Some(b)) if b > a => s[a..=b].to_string(), _ => s.to_string(), } } pub async fn agents_create(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let v = body.into_inner(); let name = match v.get("name").and_then(|n| n.as_str()) { Some(n) if !n.trim().is_empty() => n.trim().to_string(), _ => return HttpResponse::BadRequest().json(serde_json::json!({"error": "name is required"})), }; let mut agent = crate::wolfagents::new_default(name); // Apply optional overrides from the body so the create-and- // customise-in-one-call path works from the UI. if let Some(s) = v.get("system_prompt").and_then(|x| x.as_str()) { agent.system_prompt = s.to_string(); } if let Some(m) = v.get("model").and_then(|x| x.as_str()) { agent.model = m.to_string(); } if let Some(p) = v.get("provider").and_then(|x| x.as_str()) { agent.provider = p.to_string(); } if let Some(arr) = v.get("allowed_tools").and_then(|x| x.as_array()) { agent.allowed_tools = arr.iter().filter_map(|t| t.as_str().map(String::from)).collect(); } if let Some(n) = v.get("memory_max_lines").and_then(|x| x.as_u64()) { agent.memory_max_lines = (n as usize).clamp(4, 4096); } if let Some(d) = v.get("discord") && let Ok(parsed) = serde_json::from_value::(d.clone()) { agent.discord = Some(parsed); } apply_access_fields(&mut agent, &v); match crate::wolfagents::upsert(agent.clone()) { Ok(()) => HttpResponse::Ok().json(agent), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// Apply access_level + target_scope + include_cluster_context from /// the incoming JSON body to an agent record. Shared between create /// and update so the two paths stay in sync. Missing fields leave /// the existing value in place; setting target_scope to an empty /// object clears all scope restrictions (intentional — the operator /// may want to widen scope). fn apply_access_fields(agent: &mut crate::wolfagents::Agent, v: &serde_json::Value) { // Avatar: either a bare filename (e.g. "wolf-grey.svg" → served from // /images/agent-avatars/) or a data: URL from a user upload. null // clears the field, which makes the UI fall back to a deterministic // built-in pick. We cap data URLs at 512 KB to keep agents.json from // ballooning when lots of agents carry custom uploads. if let Some(v_av) = v.get("avatar") { if v_av.is_null() { agent.avatar = None; } else if let Some(s) = v_av.as_str() { let trimmed = s.trim(); if trimmed.is_empty() { agent.avatar = None; } else if trimmed.len() > 512 * 1024 { tracing::warn!( "wolfagents: rejecting avatar >512 KB for agent {} ({} bytes)", agent.id, trimmed.len()); // Preserve the existing avatar rather than failing the // whole update on this one field. } else { agent.avatar = Some(trimmed.to_string()); } } } if let Some(level) = v.get("access_level").and_then(|x| x.as_str()) { agent.access_level = match level { "read_only" => crate::wolfagents::AccessLevel::ReadOnly, "read_write" => crate::wolfagents::AccessLevel::ReadWrite, "confirm_all" => crate::wolfagents::AccessLevel::ConfirmAll, "trusted" => crate::wolfagents::AccessLevel::Trusted, _ => agent.access_level, // unknown value: keep existing }; } if let Some(scope_v) = v.get("target_scope") && let Ok(parsed) = serde_json::from_value::(scope_v.clone()) { agent.target_scope = parsed; } if let Some(b) = v.get("include_cluster_context").and_then(|x| x.as_bool()) { agent.include_cluster_context = b; } // Telegram binding: same convention as discord — null clears, // missing leaves alone, object replaces. Historically only discord // was processed here, which meant the frontend's telegram payload // silently dropped on every save and the operator saw "chat_id // set in the UI but nothing routes". if let Some(t) = v.get("telegram") { if t.is_null() { agent.telegram = None; } else if let Ok(parsed) = serde_json::from_value::(t.clone()) { agent.telegram = Some(parsed); } } // WhatsApp binding: same null/missing/object semantics. if let Some(w) = v.get("whatsapp") { if w.is_null() { agent.whatsapp = None; } else if let Ok(parsed) = serde_json::from_value::(w.clone()) { agent.whatsapp = Some(parsed); } } } /// PUT /api/agents/{id} — update fields on an existing agent. Body /// is the full agent JSON (same shape as create). Missing fields fall /// back to the stored agent's values so partial updates work. pub async fn agents_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut agent = match crate::wolfagents::load(&id) { Some(a) => a, None => return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})), }; let v = body.into_inner(); if let Some(n) = v.get("name").and_then(|x| x.as_str()) && !n.trim().is_empty() { agent.name = n.trim().to_string(); } if let Some(s) = v.get("system_prompt").and_then(|x| x.as_str()) { agent.system_prompt = s.to_string(); } if let Some(m) = v.get("model").and_then(|x| x.as_str()) { agent.model = m.to_string(); } if let Some(p) = v.get("provider").and_then(|x| x.as_str()) { agent.provider = p.to_string(); } if let Some(arr) = v.get("allowed_tools").and_then(|x| x.as_array()) { agent.allowed_tools = arr.iter().filter_map(|t| t.as_str().map(String::from)).collect(); } if let Some(n) = v.get("memory_max_lines").and_then(|x| x.as_u64()) { agent.memory_max_lines = (n as usize).clamp(4, 4096); } // Discord block: null clears the binding, missing leaves it as-is, // object replaces. if let Some(d) = v.get("discord") { if d.is_null() { agent.discord = None; } else if let Ok(parsed) = serde_json::from_value::(d.clone()) { agent.discord = Some(parsed); } } apply_access_fields(&mut agent, &v); match crate::wolfagents::upsert(agent.clone()) { Ok(()) => HttpResponse::Ok().json(agent), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// DELETE /api/agents/{id} — remove an agent and its memory. pub async fn agents_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); match crate::wolfagents::delete(&id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({"deleted": true})), Err(e) => HttpResponse::NotFound().json(serde_json::json!({"error": e})), } } #[derive(Deserialize)] pub struct AgentChatRequest { /// The user's message. No templating here — that's a WolfFlow /// concern; this endpoint is the raw chat surface. pub message: String, } /// POST /api/agents/{id}/chat — send a message to an agent and get /// its reply. Appends both sides to the agent's JSONL memory. The /// chat runs synchronously; calls with very long-running agent turns /// (future tool-use) will move to a job-queue shape — not needed yet. pub async fn agents_chat( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let msg = body.into_inner().message; if msg.trim().is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({"error": "message is empty"})); } // Dashboard chats use the full tool_use loop — Claude-provider // agents with allowed_tools can actually call the dispatcher. // Discord/Telegram/WhatsApp receivers stay on the no-AppState // `chat_with_agent` fallback because they don't plumb AppState. match crate::wolfagents::chat_with_agent_full( &id, &msg, state.get_ref(), crate::wolfagents::ChatSurface::Dashboard, ).await { Ok(reply) => HttpResponse::Ok().json(serde_json::json!({ "agent_id": id, "response": reply, })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), } } /// GET /api/agents/tools — the catalogue of tools an agent can be /// granted. Drives the checklist in the Edit Agent modal. Static — the /// set is hard-coded in the binary, so the list itself doesn't /// require auth, but we still gate behind the normal session check /// since the rest of the agent surface is authenticated. pub async fn agents_tool_catalogue(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(crate::wolfagents::tools::catalogue()) } /// GET /api/agents/{id}/pending — list pending tool-use actions for /// this agent. Each entry has {seq, tool, arguments, reason, ts_queued} /// and is status=pending (approve/deny entries with other status are /// included too so the UI can show recent history). pub async fn agents_pending_list( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if crate::wolfagents::load(&id).is_none() { return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})); } // Load everything — UI filters by status. Keeps the history // viewable on the same tab. let all = crate::wolfagents::pending::load_all(&id); HttpResponse::Ok().json(serde_json::json!({ "entries": all })) } #[derive(Deserialize)] pub struct PendingDecisionBody { #[serde(default)] pub note: Option, } /// POST /api/agents/{id}/pending/{seq}/approve — run the tool now, /// record the result. The agent sees the outcome on its next chat turn. pub async fn agents_pending_approve( req: HttpRequest, state: web::Data, path: web::Path<(String, u64)>, body: web::Json, ) -> HttpResponse { let Ok(user) = require_auth(&req, &state) else { return HttpResponse::Unauthorized().json(serde_json::json!({"error": "unauthorised"})); }; let (agent_id, seq) = path.into_inner(); let Some(agent) = crate::wolfagents::load(&agent_id) else { return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})); }; let entry = match crate::wolfagents::pending::approve(&agent_id, seq, &user, body.into_inner().note) { Ok(e) => e, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error": e})), }; // Re-run the tool with the approval in hand. Dispatcher will // re-check authorise() and see our overriding "skip_auth_for_seq" // hint — but we don't carry that yet; simplest path: call the // individual tool branch directly by simulating a Trusted agent // for just this call. let trusted = crate::wolfagents::Agent { access_level: crate::wolfagents::AccessLevel::Trusted, ..agent }; let result = crate::wolfagents::dispatch::dispatch( &trusted, &entry.tool, &entry.arguments, state.get_ref() ).await; let result_json = serde_json::json!({ "ok": result.ok, "status": result.status, "data": result.data, }); let _ = crate::wolfagents::pending::record_execution(&agent_id, seq, result_json.clone()); HttpResponse::Ok().json(serde_json::json!({ "approved": true, "seq": seq, "execution": result_json, })) } /// POST /api/agents/{id}/pending/{seq}/deny — reject the pending action. /// Agent sees the denial on next turn. pub async fn agents_pending_deny( req: HttpRequest, state: web::Data, path: web::Path<(String, u64)>, body: web::Json, ) -> HttpResponse { let Ok(user) = require_auth(&req, &state) else { return HttpResponse::Unauthorized().json(serde_json::json!({"error": "unauthorised"})); }; let (agent_id, seq) = path.into_inner(); if crate::wolfagents::load(&agent_id).is_none() { return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})); } match crate::wolfagents::pending::deny(&agent_id, seq, &user, body.into_inner().note) { Ok(entry) => HttpResponse::Ok().json(serde_json::json!({ "denied": true, "entry": entry })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), } } /// GET /api/agents/{id}/audit?limit=N — last N tool invocations for /// this agent. Included the "denied" entries so operators can see when /// the agent has tried to do things it's not allowed to do (a signal /// the system prompt and tool allowlist may be out of sync). pub async fn agents_audit( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if crate::wolfagents::load(&id).is_none() { return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})); } let limit: usize = query.get("limit") .and_then(|s| s.parse().ok()) .unwrap_or(100) .min(1000); HttpResponse::Ok().json(crate::wolfagents::tools::tail_audit(&id, limit)) } /// GET /api/agents/{id}/memory?limit=N — return the last N memory /// entries for an agent. Used by the UI to hydrate the conversation /// panel when opening an agent. Default N=40. pub async fn agents_memory( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); // Confirm the agent exists — otherwise a stale UI can keep // pulling memory for a deleted agent indefinitely. if crate::wolfagents::load(&id).is_none() { return HttpResponse::NotFound().json(serde_json::json!({"error": "agent not found"})); } let limit: usize = query.get("limit") .and_then(|s| s.parse().ok()) .unwrap_or(40) .min(500); HttpResponse::Ok().json(crate::wolfagents::load_recent_memory(&id, limit)) } // ─── WolfRun API ─── /// GET /api/wolfrun/services — list all WolfRun services pub async fn wolfrun_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster = req.query_string().split('&') .find_map(|p| p.strip_prefix("cluster=")) .map(|s| s.replace("%20", " ")); let services = state.wolfrun.list(cluster.as_deref()); HttpResponse::Ok().json(services) } /// GET /api/wolfrun/services/{id} — get a single service pub async fn wolfrun_get(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match state.wolfrun.get(&path.into_inner()) { Some(svc) => HttpResponse::Ok().json(svc), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })), } } #[derive(Deserialize)] pub struct WolfRunCreateRequest { pub name: String, pub image: Option, pub replicas: Option, pub cluster_name: String, #[serde(default)] pub runtime: Option, // "docker" (default) or "lxc" #[serde(default)] pub env: Vec, #[serde(default)] pub ports: Vec, #[serde(default)] pub volumes: Vec, #[serde(default)] pub placement: Option, // "any", "prefer:", "require:" #[serde(default)] pub restart_policy: Option, // "always", "on-failure", "never" // LXC-specific #[serde(default)] pub lxc_distribution: Option, #[serde(default)] pub lxc_release: Option, #[serde(default)] pub lxc_architecture: Option, #[serde(default)] pub failover: Option, } /// POST /api/wolfrun/services — create a new service pub async fn wolfrun_create(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let runtime = match body.runtime.as_deref().unwrap_or("docker") { "lxc" => crate::wolfrun::Runtime::Lxc, _ => crate::wolfrun::Runtime::Docker, }; // Docker requires an image if runtime == crate::wolfrun::Runtime::Docker && body.image.as_deref().unwrap_or("").is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Docker services require an image" })); } let placement = match body.placement.as_deref() { Some(p) if p.starts_with("prefer:") => crate::wolfrun::Placement::PreferNode(p[7..].to_string()), Some(p) if p.starts_with("require:") => crate::wolfrun::Placement::RequireNode(p[8..].to_string()), _ => crate::wolfrun::Placement::Any, }; let restart_policy = match body.restart_policy.as_deref() { Some("on-failure") => crate::wolfrun::RestartPolicy::OnFailure, Some("never") => crate::wolfrun::RestartPolicy::Never, _ => crate::wolfrun::RestartPolicy::Always, }; let lxc_config = if runtime == crate::wolfrun::Runtime::Lxc { Some(crate::wolfrun::LxcConfig { distribution: body.lxc_distribution.clone().unwrap_or_else(|| "ubuntu".to_string()), release: body.lxc_release.clone().unwrap_or_else(|| "jammy".to_string()), // Default to THIS host's arch (arm64 on RK3588/OrangePi), not a // hardcoded amd64 — this is the primary WolfRun-LXC create path. architecture: body.lxc_architecture.clone() .unwrap_or_else(|| crate::containers::host_container_arch().to_string()), }) } else { None }; let svc = state.wolfrun.create( body.name.clone(), body.image.clone().unwrap_or_default(), body.replicas.unwrap_or(1), body.cluster_name.clone(), body.env.clone(), body.ports.clone(), body.volumes.clone(), placement, restart_policy, runtime, lxc_config, body.failover.unwrap_or(false), ); // Broadcast to cluster peers let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_to_cluster(&wolfrun, &cluster, &secret).await; }); HttpResponse::Ok().json(svc) } /// DELETE /api/wolfrun/services/{id} — delete a service and stop all instances pub async fn wolfrun_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut destroyed: Vec = Vec::new(); let mut kept: Vec = Vec::new(); // Clean up cloned containers (names containing "wolfrun") but keep the original template if let Some(svc) = state.wolfrun.get(&id) { // Clean up LB iptables rules (subprocess-backed — blocking pool) if let Some(vip) = svc.service_ip.clone() { let _ = web::block(move || crate::wolfrun::remove_lb_rules_for_vip(&vip)).await; } let (d, k) = crate::wolfrun::destroy_service_instances( &svc, &state.cluster, &state.cluster_secret, ).await; destroyed = d; kept = k; } match state.wolfrun.delete(&id) { Some(_) => { // Tell peers about the deletion FIRST (explicit tombstone — // the services-list broadcast cannot express "gone": it skips // entirely when the list is empty and merges per-cluster, which // is how deleted services kept resurrecting), then broadcast // the updated list. let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); let deleted_id = id.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_delete(&cluster, &secret, &deleted_id).await; crate::wolfrun::broadcast_to_cluster(&wolfrun, &cluster, &secret).await; }); HttpResponse::Ok().json(serde_json::json!({ "deleted": true, "destroyed": destroyed, "kept": kept, })) } None => { // Log available service IDs for debugging let available: Vec = state.wolfrun.list(None).iter().map(|s| format!("{} ({})", s.id, s.name)).collect(); warn!("WolfRun delete: service '{}' not found. Available: {:?}", id, available); HttpResponse::NotFound().json(serde_json::json!({ "error": format!("Service not found: {}", id) })) } } } #[derive(Deserialize)] pub struct WolfRunActionRequest { pub action: String, // start, stop, restart } pub async fn wolfrun_service_action(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let action = &body.action; let svc = match state.wolfrun.get(&id) { Some(s) => s, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })), }; let runtime_path = match svc.runtime { crate::wolfrun::Runtime::Docker => "docker", crate::wolfrun::Runtime::Lxc => "lxc", }; let client = &*API_HTTP_CLIENT; let mut ok_count = 0u32; let mut fail_count = 0u32; let mut errors: Vec = Vec::new(); for inst in &svc.instances { // Skip standby instances — they're managed by the failover system if inst.standby { continue; } if let Some(node) = state.cluster.get_node(&inst.node_id) { if node.is_self { // Local container — call functions directly (avoids HTTP // self-call issues). Off the runtime: each arm shells out, // Docker start/restart sleep 1 s re-plumbing WolfNet, and // this loop runs once per instance. let runtime = svc.runtime.clone(); let action_name = action.clone(); let name = inst.container_name.clone(); let result = web::block(move || match (&runtime, action_name.as_str()) { (crate::wolfrun::Runtime::Docker, "start") => crate::containers::docker_start(&name), (crate::wolfrun::Runtime::Docker, "stop") => crate::containers::docker_stop(&name), (crate::wolfrun::Runtime::Docker, "restart") => crate::containers::docker_restart(&name), (crate::wolfrun::Runtime::Lxc, "start") => crate::containers::lxc_start(&name), (crate::wolfrun::Runtime::Lxc, "stop") => crate::containers::lxc_stop(&name), (crate::wolfrun::Runtime::Lxc, "restart") => { let _ = crate::containers::lxc_stop(&name); std::thread::sleep(std::time::Duration::from_millis(500)); crate::containers::lxc_start(&name) } _ => Err(format!("Unknown action: {}", action_name)), }) .await .unwrap_or_else(|e| Err(format!("container action task failed: {}", e))); match result { Ok(_) => { ok_count += 1; } Err(e) => { errors.push(format!("{}: {}", inst.container_name, e)); fail_count += 1; } } } else { // Remote node let api_path = format!("/api/containers/{}/{}/action", runtime_path, inst.container_name); let urls = build_node_urls(&node.address, node.port, &api_path); let payload = serde_json::json!({ "action": action }); let mut success = false; for url in &urls { match client.post(url) .timeout(std::time::Duration::from_secs(30)) .peer_auth(&state.cluster_secret) .json(&payload) .send().await { Ok(resp) if resp.status().is_success() => { let _ = resp.bytes().await; success = true; break; } Ok(resp) => { let body = resp.text().await.unwrap_or_default(); errors.push(format!("{} on {}: {}", inst.container_name, node.hostname, body)); } Err(e) => { errors.push(format!("{} on {}: {}", inst.container_name, node.hostname, e)); } } } if success { ok_count += 1; } else { fail_count += 1; } } } else { errors.push(format!("{}: node not found", inst.container_name)); fail_count += 1; } } HttpResponse::Ok().json(serde_json::json!({ "action": action, "ok": ok_count, "failed": fail_count, "errors": errors, })) } #[derive(Deserialize)] pub struct WolfRunPortForwardRequest { pub public_ip: String, pub ports: Option, // Source ports on public IP pub dest_ports: Option, // Destination ports on VIP pub protocol: String, // "tcp", "udp", "all" pub label: Option, } /// POST /api/wolfrun/services/{id}/portforward — add external port forward to service VIP pub async fn wolfrun_portforward_add(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let svc = match state.wolfrun.get(&id) { Some(s) => s, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })), }; let vip = match &svc.service_ip { Some(ip) => ip.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Service has no VIP assigned" })), }; let default_label = format!("WolfRun: {}", svc.name); let label = body.label.as_deref().unwrap_or(&default_label); match crate::networking::add_ip_mapping( &body.public_ip, &vip, body.ports.as_deref(), body.dest_ports.as_deref(), &body.protocol, label, ) { Ok(mapping) => HttpResponse::Ok().json(mapping), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/wolfrun/services/{id}/portforward — list port forwards for a service pub async fn wolfrun_portforward_list(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let svc = match state.wolfrun.get(&id) { Some(s) => s, None => return HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })), }; let vip = match &svc.service_ip { Some(ip) => ip.clone(), None => return HttpResponse::Ok().json(serde_json::json!([])), }; // Filter IP mappings that target this service's VIP let all_mappings = crate::networking::list_ip_mappings(); let service_mappings: Vec<_> = all_mappings.into_iter() .filter(|m| m.wolfnet_ip == vip) .collect(); HttpResponse::Ok().json(service_mappings) } /// DELETE /api/wolfrun/services/{id}/portforward/{rule_id} — remove a port forward pub async fn wolfrun_portforward_delete(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (_service_id, rule_id) = path.into_inner(); match crate::networking::remove_ip_mapping(&rule_id) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "deleted": true })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } #[derive(Deserialize)] pub struct WolfRunScaleRequest { pub replicas: u32, } /// POST /api/wolfrun/services/{id}/scale — scale replicas pub async fn wolfrun_scale(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if state.wolfrun.scale(&id, body.replicas) { // Trigger an immediate reconcile in the background (retry if lock held) let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { for attempt in 0..3 { if attempt > 0 { actix_web::rt::time::sleep(std::time::Duration::from_secs(5)).await; } crate::wolfrun::reconcile(&wolfrun, &cluster, &secret).await; } }); // Broadcast to cluster peers let wolfrun2 = Arc::clone(&state.wolfrun); let cluster2 = Arc::clone(&state.cluster); let secret2 = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_to_cluster(&wolfrun2, &cluster2, &secret2).await; }); HttpResponse::Ok().json(serde_json::json!({ "scaled": true, "replicas": body.replicas })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })) } } #[derive(Deserialize)] pub struct WolfRunUpdateRequest { pub image: Option, } /// POST /api/wolfrun/services/{id}/update — rolling update (change image) pub async fn wolfrun_update(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if let Some(image) = &body.image { if state.wolfrun.update_image(&id, image.clone()) { // Clear instances so reconciliation redeploys with new image state.wolfrun.update_instances(&id, Vec::new()); // Broadcast to cluster peers let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_to_cluster(&wolfrun, &cluster, &secret).await; }); HttpResponse::Ok().json(serde_json::json!({ "updated": true, "image": image })) } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })) } } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": "No image specified" })) } } #[derive(Deserialize)] pub struct WolfRunSettingsRequest { pub min_replicas: Option, pub max_replicas: Option, pub desired: Option, pub lb_policy: Option, pub allowed_nodes: Option>, pub failover: Option, } /// POST /api/wolfrun/services/{id}/settings — update service settings pub async fn wolfrun_settings(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if state.wolfrun.update_settings(&id, crate::wolfrun::ServiceSettingsUpdate { min: body.min_replicas, max: body.max_replicas, desired: body.desired, lb_policy: body.lb_policy.clone(), allowed_nodes: body.allowed_nodes.clone(), failover: body.failover }) { let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::reconcile(&wolfrun, &cluster, &secret).await; }); // Broadcast to cluster peers let wolfrun2 = Arc::clone(&state.wolfrun); let cluster2 = Arc::clone(&state.cluster); let secret2 = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_to_cluster(&wolfrun2, &cluster2, &secret2).await; }); if let Some(svc) = state.wolfrun.get(&id) { HttpResponse::Ok().json(serde_json::json!({ "updated": true, "replicas": svc.replicas, "min_replicas": svc.min_replicas, "max_replicas": svc.max_replicas, "lb_policy": svc.lb_policy, "allowed_nodes": svc.allowed_nodes, "failover": svc.failover, })) } else { HttpResponse::Ok().json(serde_json::json!({ "updated": true })) } } else { HttpResponse::NotFound().json(serde_json::json!({ "error": "Service not found" })) } } #[derive(Deserialize)] pub struct WolfRunAdoptRequest { pub name: String, // WolfRun service name pub container_name: String, // Existing container name pub node_id: String, // Node where container runs pub image: String, // Container image (for Docker) pub runtime: Option, // "docker" or "lxc" pub cluster_name: String, #[serde(default)] pub env: Vec, #[serde(default)] pub ports: Vec, #[serde(default)] pub volumes: Vec, } /// POST /api/wolfrun/services/adopt — adopt an existing container into WolfRun pub async fn wolfrun_adopt(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let runtime = match body.runtime.as_deref().unwrap_or("docker") { "lxc" => crate::wolfrun::Runtime::Lxc, _ => crate::wolfrun::Runtime::Docker, }; let svc = state.wolfrun.adopt(crate::wolfrun::AdoptService { name: body.name.clone(), container_name: body.container_name.clone(), node_id: body.node_id.clone(), image: body.image.clone(), runtime, cluster_name: body.cluster_name.clone(), env: body.env.clone(), ports: body.ports.clone(), volumes: body.volumes.clone(), }); // Broadcast to cluster peers let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::wolfrun::broadcast_to_cluster(&wolfrun, &cluster, &secret).await; }); HttpResponse::Ok().json(svc) } /// GET /api/wolfrun/failover-events — list failover events pub async fn wolfrun_failover_events(req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let service_id = query.get("service_id").map(|s| s.as_str()); let events = state.wolfrun.get_failover_events(service_id); HttpResponse::Ok().json(events) } /// POST /api/wolfrun/sync — receive WolfRun services from a cluster peer pub async fn wolfrun_sync(req: HttpRequest, state: web::Data, body: web::Json>) -> HttpResponse { // Authenticate via cluster secret (inter-node auth) or session auth let secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); // Stage 5 — gate default-secret acceptance via the shared helper. if !crate::auth::validate_inter_node_secret_from(secret, &state.cluster_secret, peer_ip(&req)) { // Also try cookie auth (in case admin calls it manually) if let Err(resp) = require_auth(&req, &state) { return resp; } } let peer_services = body.into_inner(); // Tombstoned ids are rejected by the merge and reported back so the // sender — a node that slept through the deletion — deletes its stale // copy and destroys any containers it recreated, instead of gossiping // the ghost service back forever. let deleted_ids = state.wolfrun.merge_from_peer(peer_services); HttpResponse::Ok().json(serde_json::json!({ "synced": true, "deleted_ids": deleted_ids })) } #[derive(Deserialize)] pub struct WolfRunSyncDeleteRequest { pub service_id: String, } /// POST /api/wolfrun/sync-delete — a cluster peer tells us a WolfRun /// service was deleted. Record the tombstone (even if we never held the /// service) and drop our copy. Containers are destroyed by the deleting /// node via the container action API, not here. pub async fn wolfrun_sync_delete(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { let secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !crate::auth::validate_inter_node_secret_from(secret, &state.cluster_secret, peer_ip(&req)) && let Err(resp) = require_auth(&req, &state) { return resp; } let id = body.into_inner().service_id; // Tear down this node's LB rules for the service VIP — reconcile // installs them on whichever node was leader, which may be us. if let Some(svc) = state.wolfrun.get(&id) && let Some(vip) = svc.service_ip { let _ = web::block(move || crate::wolfrun::remove_lb_rules_for_vip(&vip)).await; } let removed = state.wolfrun.remove_if_exists(&id); HttpResponse::Ok().json(serde_json::json!({ "removed": removed })) } /// POST /api/wolfrun/reconcile — trigger an immediate reconcile + broadcast pub async fn wolfrun_reconcile(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let wolfrun = Arc::clone(&state.wolfrun); let cluster = Arc::clone(&state.cluster); let secret = state.cluster_secret.clone(); // Run reconcile synchronously so the response has fresh data crate::wolfrun::reconcile(&wolfrun, &cluster, &secret).await; crate::wolfrun::broadcast_to_cluster(&wolfrun, &cluster, &secret).await; HttpResponse::Ok().json(serde_json::json!({ "reconciled": true })) } // ═══════════════════════════════════════════════ // ─── Status Page API ─── // ═══════════════════════════════════════════════ /// GET /api/statuspage/config — get full config (monitors + pages) pub async fn statuspage_config_get(req: HttpRequest, state: web::Data) -> HttpResponse { // Accept cluster secret (for inter-node pull) or cookie auth let secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); // Stage 5 — gate default-secret acceptance via the shared helper. if !crate::auth::validate_inter_node_secret_from(secret, &state.cluster_secret, peer_ip(&req)) && let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.statuspage.config.read().unwrap().clone(); HttpResponse::Ok().json(config) } /// POST /api/statuspage/config — save full config pub async fn statuspage_config_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = body.into_inner(); if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } *state.statuspage.config.write().unwrap() = config; sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "saved": true })) } /// GET /api/statuspage/monitors — list all monitors with current status /// GET /api/statuspage/container-check?runtime=&name= — probe a /// container's running state on THIS node. Called node-to-node by the /// status-page checker when a Container monitor targets a remote node /// (auth via the cluster secret through require_auth). Returns /// {"up": bool, "error": string|null}. pub async fn statuspage_container_check( req: HttpRequest, state: web::Data, query: web::Query>, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let runtime = query.get("runtime").cloned().unwrap_or_default(); let name = query.get("name").cloned().unwrap_or_default(); if runtime.is_empty() || name.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "runtime and name required" })); } // Off the async worker — docker inspect / lxc-info are blocking. let (up, err) = match web::block(move || { crate::statuspage::check_container_local(&runtime, &name) }).await { Ok(v) => v, Err(e) => (false, Some(format!("check task failed: {}", e))), }; HttpResponse::Ok().json(serde_json::json!({ "up": up, "error": err })) } pub async fn statuspage_monitors_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.statuspage.config.read().unwrap(); let monitors: Vec = config.monitors.iter().map(|m| { let status = state.statuspage.monitor_status(&m.id); let latest = state.statuspage.latest_result(&m.id); let uptime = state.statuspage.uptime_percent(&m.id); let history = state.statuspage.get_daily_uptime(&m.id); let recent_checks: Vec<_> = { let results = state.statuspage.results.read().unwrap(); results.get(&m.id) .map(|d| d.iter().rev().take(20).cloned().collect()) .unwrap_or_default() }; serde_json::json!({ "monitor": m, "status": status, "status_label": status.label(), "latest": latest, "uptime_percent": uptime, "history": history, "recent_checks": recent_checks, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "monitors": monitors })) } /// GET /api/statuspage/monitors/{id}/results — every check result this node /// holds for one monitor, oldest first, for the details-page history graph. /// Each node checks independently, so `checked_by` names the node whose view /// this is; the history lives in memory and restarts with the service. pub async fn statuspage_monitor_results(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if !state.statuspage.config.read().unwrap().monitors.iter().any(|m| m.id == id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Monitor not found" })); } let checked_by = state.cluster.get_node(&state.cluster.self_id) .map(|n| n.hostname) .unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "results": state.statuspage.result_history(&id), "checked_by": checked_by, })) } /// POST /api/statuspage/monitors — create or update a monitor pub async fn statuspage_monitor_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut monitor = body.into_inner(); { let mut config = state.statuspage.config.write().unwrap(); if let Some(existing) = config.monitors.iter_mut().find(|m| m.id == monitor.id) { // The edit form doesn't carry the reset stamp; keep the stored one // so saving a monitor can't wind it back. monitor.history_reset_at = existing.history_reset_at; *existing = monitor.clone(); } else { config.monitors.push(monitor.clone()); } if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } } // Trigger immediate check cycle so status is available right away let sp = state.statuspage.clone(); let sp_cluster = state.cluster.clone(); let sp_secret = state.cluster_secret.clone(); tokio::spawn(async move { crate::statuspage::run_checks(&sp, &sp_cluster, &sp_secret).await; }); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "saved": true, "monitor": monitor })) } /// DELETE /api/statuspage/monitors/{id} — delete a monitor pub async fn statuspage_monitor_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut config = state.statuspage.config.write().unwrap(); let before = config.monitors.len(); config.monitors.retain(|m| m.id != id); // Also remove this monitor from all pages for page in config.pages.iter_mut() { page.monitor_ids.retain(|mid| mid != &id); } if config.monitors.len() == before { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Monitor not found" })); } let _ = config.save(); drop(config); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "deleted": true })) } /// POST /api/statuspage/monitors/{id}/reset-history — wipe a monitor's uptime /// history (daily bars and recent checks) on every node in its cluster. Each /// node keeps its own history, so the reset is carried by the replicated /// `history_reset_at` stamp rather than a one-off RPC. pub async fn statuspage_monitor_reset_history(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { let caller = match require_auth(&req, &state) { Ok(u) => u, Err(resp) => return resp }; let id = path.into_inner(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); let name = { let mut config = state.statuspage.config.write().unwrap(); let Some(monitor) = config.monitors.iter_mut().find(|m| m.id == id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Monitor not found" })); }; // Strictly increasing, so peers always see it rise even if two resets // land in the same second. let previous = monitor.history_reset_at; monitor.history_reset_at = now.max(previous + 1); let name = monitor.name.clone(); if let Err(e) = config.save() { // Not persisted, so not applied: put the stamp back, or the next // broadcast would carry a reset the operator was told failed. if let Some(m) = config.monitors.iter_mut().find(|m| m.id == id) { m.history_reset_at = previous; } return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } name }; state.statuspage.clear_history(&id); tracing::info!("StatusPage: {} reset uptime history for monitor '{}' ({})", caller, name, id); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "reset": true })) } /// GET /api/statuspage/pages — list all status pages with current status pub async fn statuspage_pages_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.statuspage.config.read().unwrap(); let pages: Vec = config.pages.iter().map(|p| { let overall = state.statuspage.page_overall_status(p); // Mean uptime across the page's monitors over the same window the // bars cover (crate::statuspage::UPTIME_BAR_DAYS). let uptime_90d: Option = if p.monitor_ids.is_empty() { None } else { let uptimes: Vec = p.monitor_ids.iter() .map(|mid| state.statuspage.uptime_percent(mid)) .collect(); if uptimes.is_empty() { None } else { Some(uptimes.iter().sum::() as f64 / uptimes.len() as f64) } }; // Collect active incidents for this page let active_incidents: Vec<_> = config.incidents.iter() .filter(|i| p.incident_ids.contains(&i.id) && i.status != crate::statuspage::IncidentStatus::Resolved) .cloned() .collect(); serde_json::json!({ "page": { "id": p.id, "slug": p.slug, "title": p.title, "cluster": p.cluster, "logo_url": p.logo_url, "footer_text": p.footer_text, "theme": p.theme, "monitor_ids": p.monitor_ids, "incident_ids": p.incident_ids, "enabled": p.enabled, "incidents": active_incidents, "services": p.monitor_ids, }, "overall_status": overall, "overall_label": overall.label(), "uptime_90d": uptime_90d, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "pages": pages })) } /// POST /api/statuspage/pages — create or update a status page pub async fn statuspage_page_save(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let page = body.into_inner(); // Validate slug: lowercase alphanumeric + hyphens only if page.slug.is_empty() || !page.slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Slug must be lowercase alphanumeric with hyphens only" })); } let mut config = state.statuspage.config.write().unwrap(); // Check slug uniqueness within the same cluster (except for self) if config.pages.iter().any(|p| p.slug == page.slug && p.id != page.id && p.cluster == page.cluster) { return HttpResponse::Conflict().json(serde_json::json!({ "error": "A page with this slug already exists" })); } if let Some(existing) = config.pages.iter_mut().find(|p| p.id == page.id) { *existing = page.clone(); } else { config.pages.push(page.clone()); } if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } drop(config); // Trigger immediate check cycle so status is available right away let sp = state.statuspage.clone(); let sp_cluster = state.cluster.clone(); let sp_secret = state.cluster_secret.clone(); tokio::spawn(async move { crate::statuspage::run_checks(&sp, &sp_cluster, &sp_secret).await; }); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "saved": true, "page": page })) } /// DELETE /api/statuspage/pages/{id} — delete a status page pub async fn statuspage_page_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut config = state.statuspage.config.write().unwrap(); let before = config.pages.len(); config.pages.retain(|p| p.id != id); if config.pages.len() == before { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Page not found" })); } let _ = config.save(); drop(config); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "deleted": true })) } /// GET /api/statuspage/incidents — list all incidents pub async fn statuspage_incidents_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.statuspage.config.read().unwrap(); HttpResponse::Ok().json(serde_json::json!({ "incidents": config.incidents })) } /// POST /api/statuspage/incidents — create or update an incident pub async fn statuspage_incident_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let incident = body.into_inner(); let mut config = state.statuspage.config.write().unwrap(); if let Some(existing) = config.incidents.iter_mut().find(|i| i.id == incident.id) { // If status changed to resolved and we didn't have a resolved_at, set it if incident.status == crate::statuspage::IncidentStatus::Resolved && existing.status != crate::statuspage::IncidentStatus::Resolved { let mut updated_incident = incident.clone(); updated_incident.resolved_at = Some(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()); *existing = updated_incident; } else { *existing = incident.clone(); } } else { config.incidents.push(incident.clone()); } if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } drop(config); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "saved": true, "incident": incident })) } /// DELETE /api/statuspage/incidents/{id} — delete an incident pub async fn statuspage_incident_delete(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let mut config = state.statuspage.config.write().unwrap(); let before = config.incidents.len(); config.incidents.retain(|i| i.id != id); // Also remove this incident from all pages for page in config.pages.iter_mut() { page.incident_ids.retain(|iid| iid != &id); } if config.incidents.len() == before { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Incident not found" })); } let _ = config.save(); drop(config); sp_broadcast(&state); HttpResponse::Ok().json(serde_json::json!({ "deleted": true })) } /// Broadcast status page config to cluster peers (fire-and-forget) fn sp_broadcast(state: &web::Data) { let sp = state.statuspage.clone(); let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); actix_web::rt::spawn(async move { crate::statuspage::broadcast_to_cluster(&sp, &cluster, &secret).await; }); } /// POST /api/statuspage/sync — receive status page config from a cluster peer pub async fn statuspage_sync(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { // Authenticate via cluster secret (inter-node auth) or session auth let secret = req.headers().get("X-WolfStack-Secret") .and_then(|v| v.to_str().ok()) .unwrap_or(""); // Stage 5 — gate default-secret acceptance via the shared helper. if !crate::auth::validate_inter_node_secret_from(secret, &state.cluster_secret, peer_ip(&req)) && let Err(resp) = require_auth(&req, &state) { return resp; } let peer_config = body.into_inner(); tracing::info!("StatusPage sync: received {} pages, {} monitors, {} incidents from peer", peer_config.pages.len(), peer_config.monitors.len(), peer_config.incidents.len()); state.statuspage.merge_from_peer(peer_config); HttpResponse::Ok().json(serde_json::json!({ "synced": true })) } // ═══════════════════════════════════════════════════════════════ // ─── WolfFunctions — serverless functions across the cluster ─── // ═══════════════════════════════════════════════════════════════ /// Kick an immediate config broadcast after a mutation so peers converge /// in seconds instead of waiting for the 60s periodic tick. fn wolffunctions_broadcast_soon(state: &web::Data) { let fns = state.wolffunctions.clone(); let cluster = state.cluster.clone(); let secret = state.cluster_secret.clone(); tokio::spawn(async move { crate::wolffunctions::broadcast_to_cluster(&fns, &cluster, &secret).await; }); } /// GET /api/wolffunctions — list this cluster's functions. pub async fn wolffunctions_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster_name = local_cluster_name(&state.cluster); let functions: Vec = state.wolffunctions.config.read().unwrap().functions.iter() .filter(|f| f.cluster == cluster_name) .cloned().collect(); HttpResponse::Ok().json(serde_json::json!({ "cluster": cluster_name, "functions": functions })) } /// GET /api/wolffunctions/config — full config (peer pull bootstrap). pub async fn wolffunctions_config(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = state.wolffunctions.config.read().unwrap().clone(); HttpResponse::Ok().json(cfg) } /// POST /api/wolffunctions/sync — receive a peer's cluster-scoped function /// set. Inter-node only: requires the cluster secret strictly (no session /// fallback), because this replaces a whole cluster's functions and the UI /// never calls it — a logged-in session has no business here. merge_cluster /// clamps peer-supplied limits, so a compromised peer can't push /// out-of-range values past the create/update validation. pub async fn wolffunctions_sync( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let payload = body.into_inner(); state.wolffunctions.merge_cluster(&payload.cluster, payload.functions); HttpResponse::Ok().json(serde_json::json!({ "synced": true })) } #[derive(serde::Deserialize)] pub struct WolfFunctionUpsertBody { pub name: String, pub runtime: crate::wolffunctions::FunctionRuntime, pub code: String, #[serde(default)] pub description: String, pub memory_mb: Option, pub timeout_secs: Option, pub replicas: Option, pub max_per_node: Option, #[serde(default)] pub env: Vec, #[serde(default)] pub public_slug: Option, #[serde(default)] pub schedules: Vec, #[serde(default)] pub events: Vec, pub enabled: Option, } fn validate_upsert(body: &WolfFunctionUpsertBody) -> Result<(), String> { if !crate::wolffunctions::valid_name(&body.name) { return Err("Function name must be 1-63 chars of a-z, 0-9, and hyphens".into()); } if body.code.trim().is_empty() { return Err("Function code is empty".into()); } if body.code.len() > 512 * 1024 { return Err("Function code exceeds 512KB".into()); } if let Some(slug) = body.public_slug.as_deref() && !slug.is_empty() && !crate::wolffunctions::valid_name(slug) { return Err("Public slug must be 1-63 chars of a-z, 0-9, and hyphens".into()); } for kv in &body.env { if !kv.contains('=') || kv.starts_with('=') { return Err(format!("Environment entry '{}' is not KEY=VALUE", kv)); } } for s in &body.schedules { if s.interval_secs < 60 { return Err("Schedule intervals must be at least 60 seconds".into()); } } Ok(()) } /// POST /api/wolffunctions — create a function. pub async fn wolffunctions_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let body = body.into_inner(); if let Err(e) = validate_upsert(&body) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } let cluster_name = local_cluster_name(&state.cluster); if state.wolffunctions.get_by_name(&cluster_name, &body.name).is_some() { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!("A function named '{}' already exists in this cluster", body.name) })); } let slug = body.public_slug.clone().filter(|s| !s.is_empty()); if let Some(s) = &slug && state.wolffunctions.get_by_slug(s).is_some() { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!("Public slug '{}' is already in use", s) })); } let now = crate::wolffunctions::now_secs(); let func = crate::wolffunctions::WolfFunction { id: uuid::Uuid::new_v4().to_string(), name: body.name, cluster: cluster_name, runtime: body.runtime, code: body.code, description: body.description, memory_mb: body.memory_mb.unwrap_or(128).clamp(32, 8192), timeout_secs: body.timeout_secs.unwrap_or(30).clamp(1, 900), replicas: body.replicas.unwrap_or(2).min(64), max_per_node: body.max_per_node.unwrap_or(4).clamp(1, 32), env: body.env, placed_nodes: Vec::new(), public_slug: slug, schedules: body.schedules, events: body.events, enabled: body.enabled.unwrap_or(true), version: 1, created_at: now, updated_at: now, }; let out = serde_json::json!({ "ok": true, "function": func }); state.wolffunctions.upsert(func); wolffunctions_broadcast_soon(&state); HttpResponse::Ok().json(out) } /// PUT /api/wolffunctions/{id} — update a function. Version bumps when an /// execution-affecting field changes so warm instances get replaced. pub async fn wolffunctions_update( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let body = body.into_inner(); if let Err(e) = validate_upsert(&body) { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e })); } let Some(mut func) = state.wolffunctions.get(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Function not found" })); }; let cluster_name = func.cluster.clone(); if body.name != func.name && state.wolffunctions.get_by_name(&cluster_name, &body.name).is_some() { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!("A function named '{}' already exists in this cluster", body.name) })); } let slug = body.public_slug.clone().filter(|s| !s.is_empty()); if let Some(s) = &slug && state.wolffunctions.get_by_slug(s).map(|f| f.id != id).unwrap_or(false) { return HttpResponse::Conflict().json(serde_json::json!({ "error": format!("Public slug '{}' is already in use", s) })); } let memory_mb = body.memory_mb.unwrap_or(func.memory_mb).clamp(32, 8192); let needs_new_version = func.code != body.code || func.env != body.env || func.runtime != body.runtime || func.memory_mb != memory_mb; func.name = body.name; func.runtime = body.runtime; func.code = body.code; func.description = body.description; func.memory_mb = memory_mb; func.timeout_secs = body.timeout_secs.unwrap_or(func.timeout_secs).clamp(1, 900); func.replicas = body.replicas.unwrap_or(func.replicas).min(64); func.max_per_node = body.max_per_node.unwrap_or(func.max_per_node).clamp(1, 32); func.env = body.env; func.public_slug = slug; func.schedules = body.schedules; func.events = body.events; func.enabled = body.enabled.unwrap_or(func.enabled); if needs_new_version { func.version += 1; } func.updated_at = crate::wolffunctions::now_secs(); let out = serde_json::json!({ "ok": true, "function": func }); state.wolffunctions.upsert(func); wolffunctions_broadcast_soon(&state); HttpResponse::Ok().json(out) } /// DELETE /api/wolffunctions/{id} — remove a function. Warm instances on /// every node are torn down by each node's next reconcile pass. pub async fn wolffunctions_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); if !state.wolffunctions.remove(&id) { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Function not found" })); } wolffunctions_broadcast_soon(&state); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } /// POST /api/wolffunctions/{id}/invoke — invoke with cluster routing. /// Body is the event (any JSON). pub async fn wolffunctions_invoke( req: HttpRequest, state: web::Data, path: web::Path, body: web::Bytes, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let Some(func) = state.wolffunctions.get(&path.into_inner()) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Function not found" })); }; let event: serde_json::Value = serde_json::from_slice(&body) .unwrap_or(serde_json::Value::Null); match crate::wolffunctions::runtime::invoke_routed( &state.wolffunctions, &state.cluster, &state.cluster_secret, &func, event, "manual", ).await { Ok(result) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "result": result })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), } } /// POST /api/wolffunctions/{id}/invoke-local — invoke on THIS node only. /// Inter-node routing target; cluster secret required. pub async fn wolffunctions_invoke_local( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_cluster_auth(&req, &state) { return resp; } let Some(func) = state.wolffunctions.get(&path.into_inner()) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Function not found" })); }; let payload = body.into_inner(); let event = payload.get("event").cloned().unwrap_or(serde_json::Value::Null); let trigger = payload.get("trigger").and_then(|t| t.as_str()).unwrap_or("forwarded").to_string(); let node_name = state.cluster.get_all_nodes().iter() .find(|n| n.is_self).map(|n| n.hostname.clone()).unwrap_or_else(|| "local".into()); match crate::wolffunctions::runtime::invoke_local( &state.wolffunctions, &func, event, &trigger, &node_name, ).await { Ok(result) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "result": result })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "ok": false, "error": e })), } } /// GET /api/wolffunctions/{id}/invocations — recent invocations aggregated /// from every placed node (each node holds only its own ring buffer). pub async fn wolffunctions_invocations( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let id = path.into_inner(); let Some(func) = state.wolffunctions.get(&id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Function not found" })); }; let mut records: Vec = state.wolffunctions.recent_invocations(&id) .into_iter().map(|r| serde_json::to_value(r).unwrap_or_default()).collect(); let client = &*API_HTTP_CLIENT; for node_id in &func.placed_nodes { // placed_nodes holds canonical `ws-…` ids; get_node resolves either // registry form. Skip self (our own ring is already included above). let Some(node) = state.cluster.get_node(node_id).filter(|n| n.online && !n.is_self) else { continue; }; let path = format!("/api/wolffunctions/{}/invocations-local", id); for url in build_node_urls(&node.address, node.port, &path) { match client.get(&url) .peer_auth(&state.cluster_secret) .timeout(std::time::Duration::from_secs(5)) .send().await { Ok(resp) if resp.status().is_success() => { if let Ok(v) = resp.json::().await && let Some(arr) = v.get("invocations").and_then(|a| a.as_array()) { records.extend(arr.iter().cloned()); } break; } Ok(resp) => { drain_response(resp).await; } Err(_) => {} } } } records.sort_by_key(|r| std::cmp::Reverse(r.get("ts").and_then(|t| t.as_u64()).unwrap_or(0))); records.truncate(200); HttpResponse::Ok().json(serde_json::json!({ "invocations": records })) } /// GET /api/wolffunctions/{id}/invocations-local — this node's ring only. pub async fn wolffunctions_invocations_local( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let records = state.wolffunctions.recent_invocations(&path.into_inner()); HttpResponse::Ok().json(serde_json::json!({ "invocations": records })) } /// GET /api/wolffunctions/node-local — this node's eligibility + instances. pub async fn wolffunctions_node_local( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let elig = crate::wolffunctions::runtime::probe_eligibility(&state.wolffunctions).await; let instances: Vec = state.wolffunctions.instances .lock().unwrap().values().flatten().cloned().collect(); HttpResponse::Ok().json(serde_json::json!({ "eligibility": elig, "instances": instances })) } /// GET /api/wolffunctions/overview — functions + per-node runtime state for /// the dashboard (fans out to same-cluster peers). pub async fn wolffunctions_overview( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cluster_name = local_cluster_name(&state.cluster); let functions: Vec = state.wolffunctions.config.read().unwrap().functions.iter() .filter(|f| f.cluster == cluster_name).cloned().collect(); let mut nodes_out: Vec = Vec::new(); let nodes = state.cluster.get_all_nodes(); let client = &*API_HTTP_CLIENT; for node in nodes.iter().filter(|n| { n.cluster_name.as_deref().unwrap_or("WolfStack") == cluster_name }) { if node.is_self { let elig = crate::wolffunctions::runtime::probe_eligibility(&state.wolffunctions).await; let instances: Vec = state.wolffunctions.instances .lock().unwrap().values().flatten().cloned().collect(); nodes_out.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "online": true, "eligibility": elig, "instances": instances, })); continue; } if !node.online { nodes_out.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "online": false, })); continue; } let mut fetched = false; for url in build_node_urls(&node.address, node.port, "/api/wolffunctions/node-local") { match client.get(&url) .peer_auth(&state.cluster_secret) .timeout(std::time::Duration::from_secs(8)) .send().await { Ok(resp) if resp.status().is_success() => { if let Ok(mut v) = resp.json::().await { v["node_id"] = serde_json::json!(node.id); v["hostname"] = serde_json::json!(node.hostname); v["online"] = serde_json::json!(true); nodes_out.push(v); fetched = true; } break; } Ok(resp) => { drain_response(resp).await; } Err(_) => {} } } if !fetched { nodes_out.push(serde_json::json!({ "node_id": node.id, "hostname": node.hostname, "online": true, "error": "node did not answer the runtime probe", })); } } HttpResponse::Ok().json(serde_json::json!({ "cluster": cluster_name, "functions": functions, "nodes": nodes_out, })) } /// POST /api/wolffunctions/ai-generate — generate handler code with the /// configured AI provider. Returns code for the editor; nothing deploys /// until the operator reviews and saves. pub async fn wolffunctions_ai_generate( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let prompt = body.get("prompt").and_then(|p| p.as_str()).unwrap_or("").trim().to_string(); if prompt.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Describe what the function should do" })); } let runtime: crate::wolffunctions::FunctionRuntime = match serde_json::from_value(body.get("runtime").cloned().unwrap_or_default()) { Ok(r) => r, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Unknown runtime" })), }; let cfg = crate::ai::AiConfig::load(); if !cfg.is_configured() { return HttpResponse::Ok().json(serde_json::json!({ "error": "No AI provider is configured — set one up under AI Assistant settings first" })); } let contract = match runtime { crate::wolffunctions::FunctionRuntime::Python312 => "You write WolfFunctions serverless handlers in Python 3.12.\n\ The handler is a SINGLE file that defines exactly:\n\ def handler(event, context):\n\ `event` is the trigger payload (dict or None); `context` is a dict with\n\ function/version/memory_mb/node/trigger keys. The return value must be\n\ JSON-serializable. Only the Python standard library is available —\n\ no pip packages. print() output becomes the invocation log.\n\ When the function is called over its public HTTP URL and you need to\n\ control the HTTP response (status, content type, or serve HTML/text/\n\ redirects), return an AWS-Lambda-proxy-style dict:\n\ {'statusCode': 200, 'headers': {'Content-Type': 'text/html'},\n\ 'body': '...'}. `body` must be a string; set\n\ 'isBase64Encoded': True and base64-encode `body` for binary responses.\n\ Without a numeric statusCode the return value is sent as JSON.\n\ Respond with ONLY the complete file content — no explanations, no\n\ markdown fences.", crate::wolffunctions::FunctionRuntime::Node22 => "You write WolfFunctions serverless handlers for Node.js 22.\n\ The handler is a SINGLE CommonJS file that defines exactly:\n\ exports.handler = async (event, context) => { ... }\n\ `event` is the trigger payload; `context` has function/version/\n\ memory_mb/node/trigger keys. The return value must be JSON-serializable.\n\ Only Node's standard library is available — no npm packages.\n\ console.log output becomes the invocation log.\n\ When the function is called over its public HTTP URL and you need to\n\ control the HTTP response (status, content type, or serve HTML/text/\n\ redirects), return an AWS-Lambda-proxy-style object:\n\ { statusCode: 200, headers: { 'Content-Type': 'text/html' },\n\ body: '...' }. `body` must be a string; set\n\ isBase64Encoded: true and base64-encode `body` for binary responses.\n\ Without a numeric statusCode the return value is sent as JSON.\n\ Respond with ONLY the complete file content — no explanations, no\n\ markdown fences.", }; match crate::ai::simple_chat(&cfg, contract, &[], &prompt).await { Ok(raw) => { // Strip markdown fences if the model added them anyway. let mut code = raw.trim().to_string(); if code.starts_with("```") { code = code.lines().skip(1) .take_while(|l| !l.trim_start().starts_with("```")) .collect::>().join("\n"); } HttpResponse::Ok().json(serde_json::json!({ "ok": true, "code": code })) } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": format!("AI generation failed: {}", e) })), } } /// GET /api/wolffunctions/settings-local — this node's execution settings. pub async fn wolffunctions_settings_local_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = crate::wolffunctions::runtime::LocalConfig::load(); let elig = crate::wolffunctions::runtime::probe_eligibility(&state.wolffunctions).await; HttpResponse::Ok().json(serde_json::json!({ "settings": cfg, "eligibility": elig })) } /// POST /api/wolffunctions/settings-local — change this node's execution /// mode (auto/gvisor/docker). Re-probes eligibility immediately so the UI /// reflects the outcome, and existing sandboxes are replaced by reconcile. pub async fn wolffunctions_settings_local_set( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let cfg = body.into_inner(); cfg.save(); crate::wolffunctions::runtime::reset_eligibility(&state.wolffunctions); let elig = crate::wolffunctions::runtime::probe_eligibility(&state.wolffunctions).await; HttpResponse::Ok().json(serde_json::json!({ "ok": true, "settings": cfg, "eligibility": elig })) } /// Public trigger rate limit: per-slug fixed window. Public surfaces get /// abuse protection by default. NOTE: this is per-NODE in-memory state, so a /// slug reachable via N cluster nodes tolerates up to N×this rate overall — /// it's a basic per-node abuse guard, not a cluster-wide quota. static WOLFFN_PUBLIC_RL: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); const WOLFFN_PUBLIC_RL_PER_MIN: u32 = 60; /// Map a WolfFunctions handler result to the HTTP response served on the /// public `/fn/{slug}` trigger. /// /// If the function returns an AWS Lambda proxy-integration shape — an object /// with a numeric `statusCode`, plus optional `headers`, `body` (string), and /// `isBase64Encoded` — honour it, so functions can serve HTML, redirects, or /// any content type (this is what AWS API Gateway / GCP HTTP functions do, and /// what our own docs example returns). Otherwise fall back to JSON-encoding the /// whole result with `application/json` (unchanged legacy behaviour). /// /// `multiValueHeaders` (AWS's mechanism for genuinely repeating a header, e.g. /// multiple `Set-Cookie`) is not supported — the single `headers` map is the /// documented contract; each header name appears at most once on the wire. fn wolffn_result_to_response(result: &serde_json::Value) -> HttpResponse { use actix_web::http::header::{HeaderName, HeaderValue, CONTENT_TYPE}; // Only an object carrying a numeric statusCode is treated as proxy-shaped; // anything else keeps the legacy JSON behaviour. let obj = match result.as_object() { Some(o) if o.get("statusCode").and_then(|v| v.as_u64()).is_some() => o, _ => return HttpResponse::Ok().json(result), }; let status = obj.get("statusCode").and_then(|v| v.as_u64()) .and_then(|n| u16::try_from(n).ok()) .and_then(|n| actix_web::http::StatusCode::from_u16(n).ok()) .unwrap_or(actix_web::http::StatusCode::OK); // Collect function-supplied headers into a case-insensitive map before // emitting, so a result with two case-variant keys (e.g. "Content-Type" // AND "content-type" — distinct keys in a JSON object) can't put duplicate, // conflicting headers on the wire (a content-type-confusion / cache- // poisoning vector on this public surface). `HeaderName` is stored // lowercased by the http crate, so the map dedups case variants; last value // wins. Framing headers actix must own are dropped; any name/value the http // crate rejects (e.g. CRLF-injection attempts) is skipped, not fatal. let mut hdrs: std::collections::HashMap = std::collections::HashMap::new(); if let Some(headers) = obj.get("headers").and_then(|v| v.as_object()) { for (k, v) in headers { let val = match v { serde_json::Value::String(s) => s.clone(), serde_json::Value::Number(n) => n.to_string(), serde_json::Value::Bool(b) => b.to_string(), _ => continue, }; let lk = k.to_ascii_lowercase(); if lk == "content-length" || lk == "transfer-encoding" || lk == "connection" { continue; } if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(&val)) { hdrs.insert(name, value); } } } // Body: a string is served as-is (base64-decoded to binary when the // function sets isBase64Encoded); a non-string body is JSON-encoded. let is_b64 = obj.get("isBase64Encoded").and_then(|v| v.as_bool()).unwrap_or(false); let body_bytes: Vec = match obj.get("body") { Some(serde_json::Value::String(s)) => { if is_b64 { use base64::Engine; base64::engine::general_purpose::STANDARD.decode(s).unwrap_or_default() } else { s.clone().into_bytes() } } Some(serde_json::Value::Null) | None => Vec::new(), Some(other) => { if hdrs.contains_key(&CONTENT_TYPE) { // Malformed function output: an explicit content-type but a // non-string body we can only JSON-encode. Serve JSON but leave // a breadcrumb so the author can diagnose the mismatch. tracing::debug!("WolfFunctions: handler set an explicit Content-Type but returned a non-string body; JSON-encoding it (set `body` to a string to control the payload)"); } serde_json::to_vec(other).unwrap_or_default() } }; // AWS defaults proxy responses with no explicit content-type to JSON. hdrs.entry(CONTENT_TYPE) .or_insert_with(|| HeaderValue::from_static("application/json")); let mut builder = HttpResponse::build(status); for (name, value) in hdrs { builder.append_header((name, value)); } builder.body(body_bytes) } /// GET/POST /fn/{slug} — public HTTP trigger. No auth by design (the /// operator opted in per function); errors are generic so nothing internal /// leaks through a public surface — details live in the invocation log. pub async fn wolffunctions_public_trigger( req: HttpRequest, state: web::Data, path: web::Path, body: web::Bytes, ) -> HttpResponse { let slug = path.into_inner(); let Some(func) = state.wolffunctions.get_by_slug(&slug) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "not found" })); }; if !func.enabled { return HttpResponse::NotFound().json(serde_json::json!({ "error": "not found" })); } { let now = crate::wolffunctions::now_secs(); let mut rl = WOLFFN_PUBLIC_RL.lock().unwrap(); let entry = rl.entry(slug.clone()).or_insert((now, 0)); if now.saturating_sub(entry.0) >= 60 { *entry = (now, 0); } entry.1 += 1; if entry.1 > WOLFFN_PUBLIC_RL_PER_MIN { return HttpResponse::TooManyRequests().json(serde_json::json!({ "error": "rate limited" })); } } let body_json: serde_json::Value = serde_json::from_slice(&body) .unwrap_or_else(|_| serde_json::Value::String(String::from_utf8_lossy(&body).to_string())); let event = serde_json::json!({ "trigger": "http", "method": req.method().as_str(), "query": req.query_string(), "body": body_json, "source_ip": req.peer_addr().map(|a| a.ip().to_canonical().to_string()).unwrap_or_default(), }); match crate::wolffunctions::runtime::invoke_routed( &state.wolffunctions, &state.cluster, &state.cluster_secret, &func, event, "http", ).await { Ok(result) => wolffn_result_to_response(&result), Err(e) => { tracing::warn!("WolfFunctions: public trigger {} failed: {}", slug, e); HttpResponse::InternalServerError().json(serde_json::json!({ "error": "function error" })) } } } /// Get the local cluster name from cluster state fn local_cluster_name(cluster: &crate::agent::ClusterState) -> String { let nodes = cluster.nodes_read(); nodes.get(&cluster.self_id) .and_then(|n| n.cluster_name.clone()) .unwrap_or_else(|| "WolfStack".to_string()) } /// GET /status — public index listing all enabled status pages (or redirect if only one) pub async fn statuspage_public_index(state: web::Data) -> HttpResponse { let cluster_name = local_cluster_name(&state.cluster); let html = crate::statuspage::render_index_page(&state.statuspage, &cluster_name); HttpResponse::Ok().content_type("text/html; charset=utf-8").body(html) } /// GET /status/{slug} — public status page for a specific application pub async fn statuspage_public_page(state: web::Data, path: web::Path) -> HttpResponse { let slug = path.into_inner(); let cluster_name = local_cluster_name(&state.cluster); match crate::statuspage::render_public_page(&state.statuspage, &slug, &cluster_name) { Some(html) => HttpResponse::Ok().content_type("text/html; charset=utf-8").body(html), None => { // Log what we have vs what we're looking for let config = state.statuspage.config.read().unwrap(); let available: Vec = config.pages.iter() .map(|p| format!("{}(cluster={})", p.slug, p.cluster)) .collect(); tracing::warn!("Status page 404: slug='{}' cluster='{}' — available pages: {:?}", slug, cluster_name, available); drop(config); HttpResponse::NotFound().content_type("text/html; charset=utf-8").body( r#"Not Found

Status page not found.

"# ) }, } } // ─── Configurator API ─── /// Query parameters for targeting a container or the host #[derive(Debug, Deserialize)] pub struct ConfiguratorTarget { pub runtime: Option, pub target: Option, } /// Parse query params into an ExecTarget fn parse_exec_target(query: &web::Query) -> Result { use crate::configurator::ExecTarget; match (query.runtime.as_deref(), query.target.as_deref()) { (None, None) | (Some("host"), _) => Ok(ExecTarget::Host), (Some("docker"), Some(name)) if !name.is_empty() => Ok(ExecTarget::Docker(name.to_string())), (Some("lxc"), Some(name)) if !name.is_empty() => Ok(ExecTarget::Lxc(name.to_string())), (Some(rt), None) | (Some(rt), Some("")) => Err(HttpResponse::BadRequest().json( serde_json::json!({"error": format!("runtime '{}' requires a 'target' parameter", rt)}) )), (Some(rt), _) => Err(HttpResponse::BadRequest().json( serde_json::json!({"error": format!("Unsupported runtime: '{}'", rt)}) )), (None, Some(_)) => Err(HttpResponse::BadRequest().json( serde_json::json!({"error": "'target' requires a 'runtime' parameter"}) )), } } /// GET /api/configurator/nginx/sites — list all nginx sites pub async fn nginx_list_sites(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::nginx::list_sites(&target)).await { Ok(Ok(sites)) => HttpResponse::Ok().json(serde_json::json!({ "sites": sites })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/nginx/sites/{name} — read a site config pub async fn nginx_read_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::nginx::read_site(&target, &name)).await { Ok(Ok(content)) => HttpResponse::Ok().json(serde_json::json!({ "content": content })), Ok(Err(e)) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct SiteConfigRequest { pub name: Option, pub content: String, } /// POST /api/configurator/nginx/sites — create a new site pub async fn nginx_create_site(req: HttpRequest, state: web::Data, body: web::Json, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = match &body.name { Some(n) => n.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Name is required" })), }; let content = body.content.clone(); match web::block(move || crate::configurator::nginx::save_site(&target, &name, &content)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// PUT /api/configurator/nginx/sites/{name} — update a site config pub async fn nginx_update_site(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); let content = body.content.clone(); match web::block(move || crate::configurator::nginx::save_site(&target, &name, &content)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/nginx/available-certs — list installed /// Let's Encrypt certs visible to the configurator target. /// /// Target-aware: honours `?runtime=docker|lxc&target=name` the same way /// the sibling site-CRUD endpoints do. Container targets see their own /// `/etc/letsencrypt/live/` (which is empty unless certbot ran inside /// them or the host's `/etc/letsencrypt` is bind-mounted in). The /// previous host-only behaviour caused exactly this bug: operators /// configuring an LXC nginx site picked a host cert from the dropdown, /// got cert paths that didn't exist inside the LXC, and nginx failed /// to start. Refusing to silently leak host certs into a container /// context is the correct call — frontend renders an explicit empty /// state with bind-mount instructions. /// /// Wildcards (`*.zone`) are tagged so the UI can swap the server-name /// textbox for a "subdomain + zone-chip" pair and synthesise the final /// hostname (e.g. `myhost` + `*.wolf.uk.com` → `myhost.wolf.uk.com`). pub async fn nginx_available_certs( req: HttpRequest, state: web::Data, query: web::Query, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; // Surface what the dropdown is reading so the UI can render the // right empty-state copy ("no certs on this host" vs "no certs in // this LXC — bind-mount /etc/letsencrypt or run certbot inside"). let target_kind = match &target { crate::configurator::ExecTarget::Host => "host", crate::configurator::ExecTarget::Docker(_) => "docker", crate::configurator::ExecTarget::Lxc(_) => "lxc", }; let target_name = match &target { crate::configurator::ExecTarget::Host => String::new(), crate::configurator::ExecTarget::Docker(n) | crate::configurator::ExecTarget::Lxc(n) => n.clone(), }; // Subprocess fan-out (one openssl-per-cert) — keep it off the actix // worker thread. let probe_target = target.clone(); let certs = match web::block(move || crate::certbot::list_certs_via_target(&probe_target)).await { Ok(v) => v, Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("cert probe failed: {}", e) })), }; HttpResponse::Ok().json(serde_json::json!({ "certs": certs, "target_kind": target_kind, "target_name": target_name, })) } /// DELETE /api/configurator/nginx/sites/{name} — delete a site pub async fn nginx_delete_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::nginx::delete_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/nginx/sites/{name}/enable pub async fn nginx_enable_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::nginx::enable_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/nginx/sites/{name}/disable pub async fn nginx_disable_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::nginx::disable_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/nginx/test — run nginx -t pub async fn nginx_test_config(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::nginx::test_config(&target)).await { Ok(result) => HttpResponse::Ok().json(result), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/nginx/reload — reload nginx pub async fn nginx_reload(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::nginx::reload(&target)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/nginx/error-log — recent error log pub async fn nginx_error_log(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::nginx::error_log(&target, 100)).await { Ok(lines) => HttpResponse::Ok().json(serde_json::json!({ "lines": lines })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/nginx/generate — generate nginx config from form params pub async fn nginx_generate_config(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::configurator::nginx::generate_site_config(&body); HttpResponse::Ok().json(serde_json::json!({ "config": config })) } /// POST /api/configurator/nginx/bootstrap — install nginx and create default config pub async fn nginx_bootstrap(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::nginx::bootstrap_nginx(&target)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── Apache Configurator API ─── /// GET /api/configurator/apache/sites — list all Apache vhosts pub async fn apache_list_sites(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::list_sites(&target)).await { Ok(Ok(sites)) => HttpResponse::Ok().json(serde_json::json!({ "sites": sites })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/apache/sites/{name} — read a vhost config pub async fn apache_read_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::read_site(&target, &name)).await { Ok(Ok(content)) => HttpResponse::Ok().json(serde_json::json!({ "content": content })), Ok(Err(e)) => HttpResponse::NotFound().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/sites — create a new vhost pub async fn apache_create_site(req: HttpRequest, state: web::Data, body: web::Json, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = match &body.name { Some(n) => n.clone(), None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Name is required" })), }; let content = body.content.clone(); match web::block(move || crate::configurator::apache::save_site(&target, &name, &content)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// PUT /api/configurator/apache/sites/{name} — update a vhost config pub async fn apache_update_site(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); let content = body.content.clone(); match web::block(move || crate::configurator::apache::save_site(&target, &name, &content)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// DELETE /api/configurator/apache/sites/{name} — delete a vhost pub async fn apache_delete_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::delete_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/sites/{name}/enable pub async fn apache_enable_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::enable_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/sites/{name}/disable pub async fn apache_disable_site(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::disable_site(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/apache/modules — list Apache modules pub async fn apache_list_modules(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::list_modules(&target)).await { Ok(Ok(mods)) => HttpResponse::Ok().json(serde_json::json!({ "modules": mods })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/modules/{name}/enable pub async fn apache_enable_module(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::enable_module(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/modules/{name}/disable pub async fn apache_disable_module(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let name = path.into_inner(); match web::block(move || crate::configurator::apache::disable_module(&target, &name)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/test — run apachectl configtest pub async fn apache_test_config(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::test_config(&target)).await { Ok(result) => HttpResponse::Ok().json(result), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/reload — reload Apache pub async fn apache_reload(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::reload(&target)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/apache/error-log — recent error log pub async fn apache_error_log(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::error_log(&target, 100)).await { Ok(lines) => HttpResponse::Ok().json(serde_json::json!({ "lines": lines })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/apache/generate — generate Apache vhost from form params pub async fn apache_generate_config(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::configurator::apache::generate_vhost_config(&body); HttpResponse::Ok().json(serde_json::json!({ "config": config })) } /// POST /api/configurator/apache/bootstrap — install Apache and create default config pub async fn apache_bootstrap(req: HttpRequest, state: web::Data, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; match web::block(move || crate::configurator::apache::bootstrap_apache(&target)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── TOML Configurator API ─── /// GET /api/configurator/toml/{component}/structured — parsed config as JSON pub async fn toml_get_structured(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let component = path.into_inner(); match web::block(move || crate::configurator::toml_editor::parse_config(&target, &component)).await { Ok(Ok(data)) => HttpResponse::Ok().json(data), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/toml/{component}/structured — save JSON as TOML pub async fn toml_save_structured(req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let component = path.into_inner(); let data = body.into_inner(); match web::block(move || crate::configurator::toml_editor::save_config(&target, &component, &data)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(Deserialize)] pub struct TomlValidateRequest { pub content: String, } /// POST /api/configurator/toml/{component}/validate — validate TOML string pub async fn toml_validate(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let content = body.content.clone(); match crate::configurator::toml_editor::validate_toml(&content) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "valid": true })), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "valid": false, "error": e })), } } /// POST /api/configurator/toml/{component}/bootstrap — create default TOML config pub async fn toml_bootstrap(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let component = path.into_inner(); match web::block(move || crate::configurator::toml_editor::bootstrap_config(&target, &component)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/configurator/toml/{component}/repair — fill in any /// required keys missing from the on-disk config using the default /// template. User-set values are preserved untouched. The UI offers /// this when /validate-fields returns a non-empty list. pub async fn toml_repair(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let component = path.into_inner(); match web::block(move || crate::configurator::toml_editor::repair_config(&target, &component)).await { Ok(Ok(msg)) => HttpResponse::Ok().json(serde_json::json!({ "message": msg })), Ok(Err(e)) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/configurator/toml/{component}/validate-fields — list any /// keys present in the default template but absent from the on-disk /// config. The editor calls this alongside /structured on every load /// so it can surface a warning + Repair button. pub async fn toml_validate_fields(req: HttpRequest, state: web::Data, path: web::Path, query: web::Query) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let target = match parse_exec_target(&query) { Ok(t) => t, Err(r) => return r }; let component = path.into_inner(); match web::block(move || crate::configurator::toml_editor::validate_config(&target, &component)).await { Ok(Ok(missing)) => HttpResponse::Ok().json(serde_json::json!({ "missing_required": missing })), Ok(Err(e)) => HttpResponse::Ok().json(serde_json::json!({ "missing_required": [], "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ─── Patreon Integration ───────────────────────────────────────────────────── /// GET /api/patreon/connect — start OAuth flow, redirect to Patreon async fn patreon_connect(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Build the callback URL for this WolfStack instance let conn = req.connection_info(); let scheme = conn.scheme(); let host = conn.host(); let callback_url = format!("{}://{}/api/patreon/callback", scheme, host); let auth_url = state.patreon.authorize_url(&callback_url); HttpResponse::Found() .append_header(("Location", auth_url)) .finish() } /// GET /api/patreon/callback — receive tokens from wolfscale.org proxy /// The proxy already exchanged the code for tokens using the client secret. /// We receive: ?access_token=...&refresh_token=... (or ?error=...) async fn patreon_callback(_req: HttpRequest, state: web::Data, query: web::Query>) -> HttpResponse { // Check for error from proxy if let Some(error) = query.get("error") { return HttpResponse::Ok().content_type("text/html").body(format!( r#"Patreon Link Failed

Patreon Link Failed

Error: {}

Return to dashboard

"#, error )); } // Receive tokens from proxy let access_token = match query.get("access_token") { Some(t) => t.clone(), None => { return HttpResponse::Ok().content_type("text/html").body( r#"Patreon Link Failed

Patreon Link Failed

No access token received

Return to dashboard

"# ); } }; let refresh_token = query.get("refresh_token").cloned().unwrap_or_default(); // Save tokens { let mut config = state.patreon.config.write().unwrap(); config.access_token = Some(access_token); config.refresh_token = Some(refresh_token); config.linked = true; let _ = config.save(); } // Immediately sync membership info match state.patreon.sync_membership().await { Ok(tier) => { tracing::info!("Patreon linked successfully, tier: {:?}", tier); } Err(e) => { tracing::warn!("Patreon linked but membership sync failed: {}", e); } } HttpResponse::Ok().content_type("text/html").body( r#"Patreon Linked

Patreon Linked Successfully!

Your support tier has been detected. You can close this window.

Return to dashboard

"# ) } /// GET /api/patreon/status — return current Patreon link status and tier async fn patreon_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = state.patreon.config.read().unwrap(); let (beta_ok, beta_reason) = beta_access_granted_full(&config.tier, config.github_sponsor); HttpResponse::Ok().json(serde_json::json!({ "linked": config.linked, "user_name": config.patreon_user_name, "email": config.patreon_email, "tier": config.tier, "pledge_amount_cents": config.pledge_amount_cents, "has_beta_access": beta_ok, "beta_access_reason": beta_reason, "github_sponsor": config.github_sponsor, "github_sponsor_login": config.github_sponsor_login, "last_checked": config.last_checked, })) } /// POST /api/sponsor/github — toggle the GitHub Sponsor self-attest /// flag (operator-session auth). Body: `{ "enabled": bool, /// "login": Option }`. The `login` is for display purposes /// only — never part of the access check. See `beta_access_granted_full` /// for the reasoning behind the honour-system design. #[derive(serde::Deserialize)] struct SetGithubSponsorRequest { enabled: bool, #[serde(default)] login: Option, } async fn set_github_sponsor( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { // Operator-session ONLY (not cluster-secret) — flipping the beta // gate is an operator decision, not a peer-driven one. let _user = match req.cookie("wolfstack_session") .and_then(|c| state.sessions.validate_info(c.value())) { Some(s) if s.read_only => return read_only_forbidden("changing the GitHub Sponsor setting"), Some(s) => s.username, None => return session_expired_response( "operator session required to change GitHub Sponsor state", ), }; let body = body.into_inner(); if let Err(e) = state.patreon.set_github_sponsor(body.enabled, body.login) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("could not persist sponsor flag: {}", e) })); } let cfg = state.patreon.config.read().unwrap(); let (beta_ok, beta_reason) = beta_access_granted_full(&cfg.tier, cfg.github_sponsor); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "github_sponsor": cfg.github_sponsor, "github_sponsor_login": cfg.github_sponsor_login, "has_beta_access": beta_ok, "beta_access_reason": beta_reason, })) } /// POST /api/patreon/sync — manually refresh membership status async fn patreon_sync(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } match state.patreon.sync_membership().await { Ok(tier) => { let config = state.patreon.config.read().unwrap(); let (beta_ok, beta_reason) = beta_access_granted(&tier); HttpResponse::Ok().json(serde_json::json!({ "ok": true, "tier": tier, "has_beta_access": beta_ok, "beta_access_reason": beta_reason, "user_name": config.patreon_user_name, "last_checked": config.last_checked, })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// Beta-channel access is identical to supporter status (see `is_supporter`): /// beta builds are a thank-you perk for EVERYONE who supports development, not /// a premium upsell, so a $3 Patreon backer gets the same early-access builds /// as a $95 one. The commercial value lives in the licence-gated features /// (plugins, API tokens, SSO, multi-tenancy), never in the beta channel. /// Historically this gated on Patreon Advanced+ ($25) while the nag exempted /// Basic+ ($3) — and an unverified GitHub self-attest granted beta for free — /// which made the levels incoherent. The grants that count: /// /// 1. **Patreon pledge** — any paying tier (Basic+, i.e. $3+/mo). /// 2. **WolfStack paid licence** — Homelab, Team, MSP/Pro, Enterprise. /// Anyone who paid for the product earns the right to test /// pre-release builds against their environment. /// 3. **GitHub Sponsor self-attest** — operator flag at /// `/etc/wolfstack/patreon.json:github_sponsor=true`, settable /// via `POST /api/sponsor/github`. Honour-system: GitHub's /// Sponsors API requires the receiving org's auth to enumerate /// sponsors, so we can't programmatically verify. The cost of a /// false claim is "stranger gets beta builds"; the cost of /// requiring verification is "real sponsors locked out by an /// OAuth flow". We optimise for the real-sponsor path. /// /// Returns (granted, reason) so the frontend can show "via licence" /// vs "via sponsor" vs "via GitHub Sponsor" if it wants to. fn beta_access_granted_full( patreon_tier: &crate::patreon::PatreonTier, github_sponsor: bool, ) -> (bool, &'static str) { // Beta == supporter. Single source of truth so the two can never drift // apart again (a paying backer must never be offered less than a free // self-attest). is_supporter(patreon_tier, github_sponsor) } /// Convenience wrapper that defaults github_sponsor=false. Retained /// for the `/api/patreon/sync` path that only knows the freshly-fetched /// Patreon tier — that response reflects the live sponsorship state, /// while the github_sponsor flag is sticky and reported separately. fn beta_access_granted(patreon_tier: &crate::patreon::PatreonTier) -> (bool, &'static str) { beta_access_granted_full(patreon_tier, false) } /// Whether this installation supports WolfStack by ANY means — a paid /// licence, a paying Patreon pledge (Basic+), or the GitHub Sponsor /// self-attest flag. Deliberately broader than `beta_access_granted_full`: /// the login-time support nag must exempt EVERYONE who gives us money, /// including Patreon Basic backers who don't earn beta access. Nagging a /// paying customer is a self-own. /// /// Returns (is_supporter, reason) so the frontend can tailor copy if it wants. fn is_supporter( patreon_tier: &crate::patreon::PatreonTier, github_sponsor: bool, ) -> (bool, &'static str) { if crate::compat::platform_ready() { return (true, "licence"); } if patreon_tier.is_paying() { return (true, "patreon"); } if github_sponsor { return (true, "github_sponsor"); } (false, "none") } /// GET /api/value-receipt — the numbers behind the dashboard "value /// receipt" support card: how long this install has been running and /// what it's watching right now. Everything comes from in-memory state /// except the install-date marker (tiny file, read on the blocking /// pool). Stats that don't apply are omitted (null) — the frontend /// renders only what exists, never a fake zero. async fn value_receipt(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let install_epoch = web::block(install_date_epoch).await.unwrap_or_default(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let install_days = install_epoch.map(|e| now.saturating_sub(e) / 86_400); let (nodes_total, nodes_online, docker, lxc, vms, compose) = { let nodes = state.cluster.nodes_read(); let mut online = 0u32; let (mut d, mut l, mut v, mut c) = (0u32, 0u32, 0u32, 0u32); for n in nodes.values() { if n.online { online += 1; } d += n.docker_count; l += n.lxc_count; v += n.vm_count; c += n.compose_count; } (nodes.len() as u32, online, d, l, v, c) }; let monitors = state.statuspage.config.read().map(|c| c.monitors.len()).unwrap_or(0); let blocked_now = crate::predictive::threat_intel::last_synced_blocklist_len(); HttpResponse::Ok().json(serde_json::json!({ "install_days": install_days, "nodes_total": nodes_total, "nodes_online": nodes_online, "docker": docker, "lxc": lxc, "vms": vms, "compose": compose, "monitors": monitors, "blocked_now": blocked_now, })) } /// Read (or backfill) the install-date marker. Installs that predate /// the marker get their true-ish age from the oldest mtime among /// long-lived config files — node_id and ports.json are written once /// at first startup — and the result is persisted so the age is /// stable from then on. Returns None only when nothing is readable /// (the frontend then skips the age-gated card entirely — fail quiet, /// never fail loud on a goodwill feature). fn install_date_epoch() -> Option { const MARKER: &str = "/etc/wolfstack/install_date"; if let Ok(s) = std::fs::read_to_string(MARKER) && let Ok(v) = s.trim().parse::() { return Some(v); } let oldest = ["/etc/wolfstack/node_id", "/etc/wolfstack/ports.json", "/etc/wolfstack/join-token"] .iter() .filter_map(|p| std::fs::metadata(p).ok()) .filter_map(|m| m.modified().ok()) .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| d.as_secs()) .min()?; let _ = std::fs::write(MARKER, oldest.to_string()); Some(oldest) } /// GET /api/supporter/status — drives the login-time support nag. Reports /// whether this install supports WolfStack by any means (licence, paying /// Patreon pledge, or GitHub Sponsor self-attest) so the frontend can decide /// whether to show the nag. Operator session required. async fn supporter_status(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // Copy the two inputs out and drop the guard BEFORE the (sync) licence // check — never hold the RwLock guard longer than the read needs. let (tier, github_sponsor) = { let config = state.patreon.config.read().unwrap(); (config.tier.clone(), config.github_sponsor) }; let (granted, reason) = is_supporter(&tier, github_sponsor); HttpResponse::Ok().json(serde_json::json!({ "is_supporter": granted, "reason": reason, })) } /// POST /api/patreon/disconnect — unlink Patreon account async fn patreon_disconnect(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = state.patreon.config.write().unwrap(); *config = crate::patreon::PatreonConfig::default(); let _ = config.save(); HttpResponse::Ok().json(serde_json::json!({ "ok": true })) } // ─── Icon Pack Endpoints ─── /// GET /api/icon-packs — list all available icon packs (system + custom) async fn icon_packs_list(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } // read_dir over every icon theme on the box — blocking, never on a worker. let packs = match web::block(crate::icons::scan_all_packs_cached).await { Ok(p) => p, Err(e) => { error!("icon pack scan failed: {e}"); return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": "icon pack scan failed" })); } }; HttpResponse::Ok().json(serde_json::json!({ "packs": packs })) } /// GET /api/icon-packs/semantic-names — list all supported semantic icon names async fn icon_packs_semantic_names(req: HttpRequest, state: web::Data) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } HttpResponse::Ok().json(serde_json::json!({ "names": crate::icons::semantic_names() })) } /// POST /api/icon-packs/install — install from GitHub URL { "url": "https://github.com/..." } async fn icon_packs_install(req: HttpRequest, state: web::Data, body: web::Json) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let url = match body.get("url").and_then(|v| v.as_str()) { Some(u) => u, None => return HttpResponse::BadRequest().json(serde_json::json!({ "error": "missing 'url' field" })), }; match crate::icons::install_from_github(url).await { Ok(pack) => HttpResponse::Ok().json(serde_json::json!({ "ok": true, "pack": pack })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// DELETE /api/icon-packs/{pack_id} — remove a custom-installed pack async fn icon_packs_remove(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let pack_id = path.into_inner(); match crate::icons::remove_pack(&pack_id) { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "ok": true })), Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), } } /// GET /api/icon-packs/{pack_id}/icon/{icon_name} — serve a single icon file /// Resolves semantic name → freedesktop icon → file on disk async fn icon_packs_serve(req: HttpRequest, state: web::Data, path: web::Path<(String, String)>) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let (pack_id, icon_name) = path.into_inner(); // Pack lookup, icon resolution and the file read are all synchronous // filesystem work. Selecting an icon pack fires one of these per // [data-icon] placeholder — over a thousand in a single burst — so // running them inline pinned every worker thread and stalled the whole // API (see icons::scan_all_packs_cached for the measurements). // // The outcome is an enum rather than an Option so the three distinct // failures stay distinguishable to the caller, as they were before this // moved off the worker thread. enum IconServe { Served(&'static str, Vec), PackNotFound, IconNotFound, ReadFailed(std::io::Error), } let resolved = web::block(move || { let packs = crate::icons::scan_all_packs_cached(); let pack = match packs.iter().find(|p| p.id == pack_id) { Some(p) => p, None => return IconServe::PackNotFound, }; let theme_dir = std::path::Path::new(&pack.path); let file_path = match crate::icons::resolve_icon_cached(&pack.id, theme_dir, &icon_name) { Some(f) => f, None => return IconServe::IconNotFound, }; let mime = crate::icons::icon_mime(&file_path); match std::fs::read(&file_path) { Ok(data) => IconServe::Served(mime, data), Err(e) => IconServe::ReadFailed(e), } }) .await; match resolved { Ok(IconServe::Served(mime, data)) => HttpResponse::Ok() .content_type(mime) .insert_header(("Cache-Control", "public, max-age=86400")) .body(data), Ok(IconServe::PackNotFound) => { HttpResponse::NotFound().json(serde_json::json!({ "error": "pack not found" })) } Ok(IconServe::IconNotFound) => { HttpResponse::NotFound().json(serde_json::json!({ "error": "icon not found in pack" })) } Ok(IconServe::ReadFailed(e)) => { error!("icon file read failed: {e}"); HttpResponse::InternalServerError().finish() } Err(e) => { error!("icon serve failed: {e}"); HttpResponse::InternalServerError().finish() } } } /// GET /api/icon-packs/{pack_id}/preview — serve a grid of sample icons for previewing async fn icon_packs_preview(req: HttpRequest, state: web::Data, path: web::Path) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let pack_id = path.into_inner(); // This is the single most expensive icon call: it resolves EVERY // semantic name, and a miss costs thousands of failed stat() calls. // Settings > Appearance fires one per installed pack, so it must never // run on a worker thread — and the per-icon memoisation means the // second caller pays almost nothing. let pack_id_for_block = pack_id.clone(); let result = web::block(move || { let packs = crate::icons::scan_all_packs_cached(); let pack = packs.iter().find(|p| p.id == pack_id_for_block)?; let theme_dir = std::path::Path::new(&pack.path); let names = crate::icons::semantic_names(); let available: Vec<&str> = names .iter() .copied() .filter(|name| crate::icons::resolve_icon_cached(&pack.id, theme_dir, name).is_some()) .collect(); Some((names.len(), available)) }) .await; match result { Ok(Some((total, available))) => HttpResponse::Ok().json(serde_json::json!({ "pack_id": pack_id, "total_semantic": total, "available": available, })), Ok(None) => HttpResponse::NotFound().json(serde_json::json!({ "error": "pack not found" })), Err(e) => { error!("icon pack preview failed: {e}"); HttpResponse::InternalServerError().finish() } } } // ═══════════════════════════════════════════════════════════════════ // Docker Compose Management // ═══════════════════════════════════════════════════════════════════ /// Operator-configurable root for standalone Docker Compose stacks /// (Settings → File Locations → "Compose Directory"). Defaults to /// /etc/wolfstack/compose; pointing it at an existing compose root makes every /// `/docker-compose.yml` under it appear as a managed stack. fn compose_root_dir() -> String { crate::paths::get().compose_dir } const SECRETS_FILE: &str = "/etc/wolfstack/secrets.json"; #[derive(Deserialize)] struct ComposeCreateRequest { name: String, #[serde(default)] compose_yaml: String, #[serde(default)] env_content: String, } #[derive(Deserialize)] struct ComposeFileRequest { content: String, } #[derive(Deserialize, Serialize, Clone)] struct SecretEntry { key: String, value: String, #[serde(default)] description: String, #[serde(default)] created: String, #[serde(default)] updated: String, } #[derive(Deserialize)] struct SecretRequest { key: String, #[serde(default)] value: Option, #[serde(default)] description: Option, } fn compose_project_dir(name: &str) -> std::path::PathBuf { std::path::PathBuf::from(compose_root_dir()).join(name) } /// Find the compose file in a stack directory, honouring Docker Compose's own /// filename precedence: compose.yaml > compose.yml > docker-compose.yaml > /// docker-compose.yml. Returns the existing file, or `docker-compose.yml` (our /// canonical name for newly-created stacks) when none is present yet — so /// imported stacks that use any of the standard names are picked up and edited /// in place rather than ignored or duplicated. fn compose_file_in(dir: &std::path::Path) -> std::path::PathBuf { for name in ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"] { let p = dir.join(name); if p.exists() { return p; } } dir.join("docker-compose.yml") } /// Validate compose stack name — alphanumeric, dash, underscore only fn is_safe_compose_name(name: &str) -> bool { !name.is_empty() && name.len() <= 128 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') && !name.starts_with('-') } /// Validate a name from a URL path parameter; returns Err(HttpResponse) on failure fn require_safe_compose_name(name: &str) -> Result<(), HttpResponse> { if !is_safe_compose_name(name) { Err(HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid stack name — only alphanumeric, dash, and underscore allowed" }))) } else { Ok(()) } } /// Count compose stacks (directories under the compose root that hold a compose /// file). Cheap dir scan; surfaced as a per-node count in the nav alongside /// Docker/LXC/VM so an operator sees at a glance how many stacks a node has /// (Gary/KO4BSR 2026-06-27). pub(crate) fn compose_stack_count() -> u32 { let root = compose_root_dir(); let mut n = 0u32; if let Ok(entries) = std::fs::read_dir(std::path::Path::new(&root)) { for e in entries.flatten() { let p = e.path(); if p.is_dir() && compose_file_in(&p).exists() { n += 1; } } } n } /// The image references a stack resolves to (`docker compose config --images`). fn compose_config_images(dir: &std::path::Path, compose_file: &std::path::Path) -> Vec { let mut cmd = match crate::containers::compose_cmd() { Ok(c) => c, Err(_) => return Vec::new(), }; match cmd .args(["-f", &compose_file.to_string_lossy(), "config", "--images"]) .envs(compose_secrets_env()) .current_dir(dir) .output() { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout) .lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect(), _ => Vec::new(), } } /// The local image ID for a reference, or "" when the image isn't present /// locally. Used to deterministically tell which images a pull actually changed /// (parsing pull progress text can't distinguish "downloaded" from "up to date"). fn docker_image_id(image: &str) -> String { Command::new("docker") .args(["image", "inspect", image, "-f", "{{.Id}}"]) .output() .ok() .filter(|o| o.status.success()) .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) .unwrap_or_default() } /// Snapshot of (image ref → local image ID) for every image a stack uses. fn compose_image_id_map(dir: &std::path::Path, compose_file: &std::path::Path) -> Vec<(String, String)> { compose_config_images(dir, compose_file) .into_iter() .map(|img| { let id = docker_image_id(&img); (img, id) }) .collect() } /// Extract the names of `${VAR}`s that `docker compose config` reports as /// undefined. Compose logs one warning per missing variable on stderr, e.g. /// level=warning msg="The \"FOO\" variable is not set. Defaulting to a blank string." /// We pull `FOO` out of each such line (quotes may be backslash-escaped by the /// logger, so we strip a trailing quote/backslash before reading the /// identifier). De-duplicated, order preserved (wabil 2026-06-26). pub(crate) fn parse_undefined_compose_vars(stderr: &str) -> Vec { let mut out: Vec = Vec::new(); for line in stderr.lines() { let Some(idx) = line.find("variable is not set") else { continue }; let head = line[..idx].trim_end(); // Drop the closing quote (and any escaping backslash) after the name. let head = head.trim_end_matches('"').trim_end_matches('\\'); let name: String = head.chars().rev() .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') .collect::>().into_iter().rev().collect(); if !name.is_empty() && !out.contains(&name) { out.push(name); } } out } /// Log, once Docker is reachable, every compose stack under the compose root /// that has NO containers on this host — not stopped ones, none at all. Those /// are stacks that were never brought up here (a standby that received the /// compose directory, a restored node), and nothing will start them: WolfStack /// does not run `compose up` at daemon start and Docker's restart policy only /// restarts containers that exist. Without this line "the daemon is running" /// looks healthy while half the workload is absent (Colt 2026-09-06). /// /// Blocking and bounded: waits up to five minutes for `docker info` (Docker /// is ordered after wolfstack-mounts.target, so at boot it starts AFTER this /// daemon), then one `compose ps -aq` per stack. Silent when Docker is not /// installed or never comes up — that is not this check's story to tell. pub fn warn_stacks_never_started() { if which_docker().is_none() { return; } let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); loop { let up = std::process::Command::new("docker").arg("info").output() .map(|o| o.status.success()).unwrap_or(false); if up { break; } if std::time::Instant::now() >= deadline { tracing::debug!("compose: Docker not reachable after 5 min — skipping the never-started stack check"); return; } std::thread::sleep(std::time::Duration::from_secs(10)); } let root = compose_root_dir(); let Ok(entries) = std::fs::read_dir(&root) else { return }; let mut never_started: Vec = Vec::new(); for entry in entries.flatten() { let path = entry.path(); if !path.is_dir() { continue; } let compose_file = compose_file_in(&path); if !compose_file.exists() { continue; } let Ok(mut cmd) = crate::containers::compose_cmd() else { return }; let out = cmd .args(["-f", &compose_file.to_string_lossy(), "ps", "-aq"]) .envs(compose_secrets_env()) .current_dir(&path) .output(); // A failing `ps` (bad YAML, daemon hiccup) is not "no containers" — // only a clean, empty answer counts. if let Ok(o) = out && o.status.success() && String::from_utf8_lossy(&o.stdout).trim().is_empty() { never_started.push(entry.file_name().to_string_lossy().to_string()); } } if never_started.is_empty() { return; } never_started.sort(); tracing::warn!( "compose: {} stack(s) under {} have no containers on this host — never brought up here: {}. \ WolfStack does not auto-start stacks (Docker's restart policy only restarts containers that exist); \ start them from the Compose page or with `docker compose up -d` in each directory. Stacks that \ reference ${{KEY}} secrets need those keys in this host's Secrets Manager first.", never_started.len(), root, never_started.join(", ") ); } fn which_docker() -> Option { std::env::var_os("PATH").and_then(|paths| { std::env::split_paths(&paths) .map(|d| d.join("docker")) .find(|p| p.is_file()) }) } /// Per-container final action parsed from `docker compose up -d` output, keeping /// only the most significant state per container so the UI can report what /// actually changed: lines look like " Container app-web-1 Started ". Created / /// Recreated / Started mean the container came up fresh (e.g. a pulled image was /// applied); Running means it was left untouched. Transitional lines (Creating, /// Starting, …) are dropped (wabil 2026-06-26). fn parse_compose_container_actions(output: &str) -> Vec<(String, String)> { fn rank(a: &str) -> u8 { match a { "Recreated" => 5, "Created" => 4, "Started" | "Restarted" => 3, "Running" => 1, _ => 0, // transitional / unknown — ignored } } let mut best: std::collections::BTreeMap = std::collections::BTreeMap::new(); for line in output.lines() { let t = line.trim(); let Some(rest) = t.strip_prefix("Container ") else { continue }; let rest = rest.trim(); let Some(pos) = rest.rfind(char::is_whitespace) else { continue }; let name = rest[..pos].trim().to_string(); let action = rest[pos..].trim().to_string(); if rank(&action) == 0 || name.is_empty() { continue; } let replace = best.get(&name).map(|cur| rank(&action) > rank(cur)).unwrap_or(true); if replace { best.insert(name, action); } } best.into_iter().collect() } /// GET /api/compose/stacks — list all compose projects async fn compose_list_stacks( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let compose_root = compose_root_dir(); let dir = std::path::Path::new(&compose_root); if !dir.exists() { return HttpResponse::Ok().json(serde_json::json!({ "stacks": [] })); } let mut stacks = Vec::new(); if let Ok(entries) = std::fs::read_dir(dir) { for entry in entries.flatten() { let path = entry.path(); if !path.is_dir() { continue; } let name = entry.file_name().to_string_lossy().to_string(); let compose_file = compose_file_in(&path); let env_file = path.join(".env"); if !compose_file.exists() { continue; } // Get stack status via docker compose ps let status = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &compose_file.to_string_lossy(), "ps", "--format", "json"]) .envs(compose_secrets_env()) .current_dir(&path) .output(), Err(e) => Err(std::io::Error::other(e)), }; let mut services = Vec::new(); let mut running = 0u32; let mut total = 0u32; if let Ok(out) = &status { let stdout = String::from_utf8_lossy(&out.stdout); for line in stdout.lines() { if let Ok(svc) = serde_json::from_str::(line) { total += 1; let state = svc.get("State").and_then(|s| s.as_str()).unwrap_or("unknown"); if state == "running" { running += 1; } services.push(serde_json::json!({ "name": svc.get("Service").and_then(|s| s.as_str()).unwrap_or(""), "state": state, "status": svc.get("Status").and_then(|s| s.as_str()).unwrap_or(""), "image": svc.get("Image").and_then(|s| s.as_str()).unwrap_or(""), "ports": svc.get("Publishers").unwrap_or(&serde_json::Value::Null), })); } } } let has_env = env_file.exists(); stacks.push(serde_json::json!({ "name": name, "path": path.to_string_lossy(), "running": running, "total": total, "services": services, "has_env": has_env, "status": if total == 0 { "stopped" } else if running == total { "running" } else { "partial" }, })); } } HttpResponse::Ok().json(serde_json::json!({ "stacks": stacks })) } /// POST /api/compose/stacks — create a new compose project async fn compose_create_stack( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = body.name.trim(); if let Err(e) = require_safe_compose_name(name) { return e; } let dir = compose_project_dir(name); if dir.exists() { return HttpResponse::Conflict().json(serde_json::json!({ "error": "Stack already exists" })); } if let Err(e) = std::fs::create_dir_all(&dir) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to create directory: {}", e) })); } let yaml = if body.compose_yaml.is_empty() { format!("# Docker Compose for {}\nservices:\n app:\n image: nginx:latest\n ports:\n - \"8080:80\"\n restart: unless-stopped\n", name) } else { body.compose_yaml.clone() }; if let Err(e) = std::fs::write(dir.join("docker-compose.yml"), &yaml) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write compose file: {}", e) })); } if !body.env_content.is_empty() && let Err(e) = std::fs::write(dir.join(".env"), &body.env_content) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to write .env: {}", e) })); } HttpResponse::Ok().json(serde_json::json!({ "message": "Stack created", "name": name })) } /// DELETE /api/compose/stacks/{name} — delete a compose project (runs down first) async fn compose_delete_stack( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); if !dir.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } // Run docker compose down first let compose_file = compose_file_in(&dir); let compose_down = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &compose_file.to_string_lossy(), "down", "--remove-orphans"]) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; match compose_down { Ok(out) if !out.status.success() => { warn!("compose down failed for '{}': {}", name, String::from_utf8_lossy(&out.stderr).trim()); } Err(e) => { warn!("compose down failed for '{}': {}", name, e); } _ => {} } if let Err(e) = std::fs::remove_dir_all(&dir) { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("Failed to delete: {}", e) })); } HttpResponse::Ok().json(serde_json::json!({ "message": "Stack deleted" })) } /// GET /api/compose/stacks/{name}/compose — read docker-compose.yml async fn compose_read_yaml( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let file = compose_file_in(&compose_project_dir(&name)); match std::fs::read_to_string(&file) { Ok(content) => HttpResponse::Ok().json(serde_json::json!({ "content": content })), Err(e) => HttpResponse::NotFound().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/compose/stacks/{name}/compose — write docker-compose.yml async fn compose_write_yaml( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let file = compose_file_in(&compose_project_dir(&name)); match std::fs::write(&file, &body.content) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "Saved" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/compose/stacks/{name}/env — read .env file async fn compose_read_env( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let file = compose_project_dir(&name).join(".env"); let content = std::fs::read_to_string(&file).unwrap_or_default(); HttpResponse::Ok().json(serde_json::json!({ "content": content })) } /// POST /api/compose/stacks/{name}/env — write .env file async fn compose_write_env( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let file = compose_project_dir(&name).join(".env"); match std::fs::write(&file, &body.content) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "Saved" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/compose/stacks/{name}/up — docker compose up -d async fn compose_up( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let out = match web::block(move || run_compose_up(&dir)).await { Ok(Ok(o)) => o, Ok(Err(e)) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), }; if out.success { HttpResponse::Ok().json(compose_up_report(&out)) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": out.stderr, "output": out.stdout })) } } /// `docker compose up -d --force-recreate --remove-orphans`: every /// container in the stack is recreated whether or not compose thinks it /// changed. `Up` alone recreates only what differs from the compose file, /// so a container that has drifted at runtime (a lost network alias, a /// half-applied restart, state compose cannot see) stays as it is; this /// is the button for that case (klas 2026-09-10). Same report as `Up`. async fn compose_recreate( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let out = match web::block(move || run_compose_up_with(&dir, true)).await { Ok(Ok(o)) => o, Ok(Err(e)) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), }; if out.success { let mut report = compose_up_report(&out); report["message"] = serde_json::Value::String("Stack recreated".to_string()); HttpResponse::Ok().json(report) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": out.stderr, "output": out.stdout })) } } /// What `docker compose up -d` left behind, for the report below. struct ComposeUpOutcome { success: bool, stdout: String, stderr: String, } /// `docker compose up -d --remove-orphans` in `dir`, with the Secrets /// Manager injected as process env. Blocking — call from `web::block`. /// Shared by the Compose page and a stack received from a peer, so the two /// can never run `up` differently. fn run_compose_up(dir: &std::path::Path) -> Result { run_compose_up_with(dir, false) } /// `run_compose_up`, optionally with `--force-recreate` (see /// `compose_recreate`). One place builds the command so the two can only /// ever differ by that flag. fn run_compose_up_with(dir: &std::path::Path, force_recreate: bool) -> Result { let compose_file = compose_file_in(dir); let mut c = crate::containers::compose_cmd()?; let file = compose_file.to_string_lossy(); let mut args: Vec<&str> = vec!["-f", &file, "up", "-d", "--remove-orphans"]; if force_recreate { args.push("--force-recreate"); } let out = c .args(&args) .envs(compose_secrets_env()) .current_dir(dir) .output() .map_err(|e| e.to_string())?; Ok(ComposeUpOutcome { success: out.status.success(), stdout: String::from_utf8_lossy(&out.stdout).to_string(), stderr: String::from_utf8_lossy(&out.stderr).to_string(), }) } /// The success-side `up` report: which containers came up fresh /// (Created/Recreated/Started — a pulled image was applied) vs were left /// running unchanged (wabil 2026-06-26), and which `${KEY}`s compose could /// not resolve. Compose only WARNS about those, then starts the stack with /// blank values — a silently degraded deployment, so it is reported /// alongside the success and the UI keeps it on screen until dismissed. fn compose_up_report(out: &ComposeUpOutcome) -> serde_json::Value { let combined = format!("{}{}", out.stdout, out.stderr); let actions = parse_compose_container_actions(&combined); let started: Vec<&str> = actions.iter() .filter(|(_, a)| a != "Running") .map(|(c, _)| c.as_str()).collect(); let unchanged = actions.iter().filter(|(_, a)| a == "Running").count(); let message = if actions.is_empty() { "Stack started".to_string() } else if started.is_empty() { format!("Stack up to date — {} container{} already running", unchanged, if unchanged == 1 { "" } else { "s" }) } else { format!("Started {} container{} with the latest image{}", started.len(), if started.len() == 1 { "" } else { "s" }, if unchanged > 0 { format!("; {} unchanged", unchanged) } else { String::new() }) }; let actions_json: Vec = actions.iter() .map(|(c, a)| serde_json::json!({ "container": c, "action": a })) .collect(); let unset_variables = parse_undefined_compose_vars(&combined); let message = if unset_variables.is_empty() { message } else { format!( "{}. WARNING: {} resolved to an empty string — not in this host's \ Secrets Manager or .env, so the stack is running with blank values", message, unset_variables.iter().map(|v| format!("${{{}}}", v)).collect::>().join(", ") ) }; serde_json::json!({ "message": message, "output": combined, "actions": actions_json, "started": started, "unchanged": unchanged, "unset_variables": unset_variables, }) } /// POST /api/compose/stacks/{name}/down — docker compose down async fn compose_down( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let output = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &compose_file.to_string_lossy(), "down", "--remove-orphans"]) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; match output { Ok(out) => { let stderr = String::from_utf8_lossy(&out.stderr).to_string(); if out.status.success() { HttpResponse::Ok().json(serde_json::json!({ "message": "Stack stopped", "output": stderr })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": stderr })) } } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/compose/stacks/{name}/pull — docker compose pull async fn compose_pull( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } // Snapshot image IDs before the pull so we can report which images actually // changed — pull progress text can't reliably distinguish a fresh download // from "already up to date" (wabil 2026-06-26). let before: std::collections::HashMap = compose_image_id_map(&dir, &compose_file).into_iter().collect(); let output = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &compose_file.to_string_lossy(), "pull"]) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; match output { Ok(out) => { let stderr = String::from_utf8_lossy(&out.stderr).to_string(); if out.status.success() { // Diff image IDs: a changed (or newly-present) ID means that // image was genuinely updated by this pull. let after = compose_image_id_map(&dir, &compose_file); let updated: Vec = after.iter() .filter(|(img, new_id)| { !new_id.is_empty() && before.get(img).map(|b| b != new_id).unwrap_or(true) }) .map(|(img, _)| serde_json::json!({ "image": img })) .collect(); let updated_count = updated.len(); let total = after.len(); let message = if updated_count == 0 { "All images already up to date".to_string() } else { format!("Pulled {} updated image{}", updated_count, if updated_count == 1 { "" } else { "s" }) }; HttpResponse::Ok().json(serde_json::json!({ "message": message, "output": stderr, "updated": updated, "updated_count": updated_count, "total_images": total, })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": stderr })) } } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// POST /api/compose/stacks/{name}/restart — docker compose restart async fn compose_restart( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let output = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &compose_file.to_string_lossy(), "restart"]) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; match output { Ok(out) => { let stderr = String::from_utf8_lossy(&out.stderr).to_string(); if out.status.success() { HttpResponse::Ok().json(serde_json::json!({ "message": "Stack restarted", "output": stderr })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": stderr })) } } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } /// GET /api/compose/stacks/{name}/logs — docker compose logs (last 200 lines) async fn compose_logs( req: HttpRequest, state: web::Data, path: web::Path, query: web::Query>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let lines = query.get("lines").and_then(|l| l.parse::().ok()).unwrap_or(200).min(5000); let file_str = compose_file.to_string_lossy().into_owned(); let lines_str = lines.to_string(); let mut cmd_args = vec!["-f", &file_str, "logs", "--no-color", "--tail", &lines_str]; // Validate service name to prevent argument injection let service_owned: String; if let Some(service) = query.get("service") && !service.is_empty() { if !service.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid service name" })); } service_owned = service.clone(); cmd_args.push(&service_owned); } let output = match crate::containers::compose_cmd() { Ok(mut c) => c .args(&cmd_args) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; match output { Ok(out) => { let logs = String::from_utf8_lossy(&out.stdout).to_string(); let stderr = String::from_utf8_lossy(&out.stderr).to_string(); HttpResponse::Ok().json(serde_json::json!({ "logs": format!("{}{}", logs, stderr) })) } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } #[derive(serde::Deserialize)] struct ComposeValidateBody { /// The editor's current (possibly unsaved) compose YAML. When present we /// validate THIS via a temp file rather than the on-disk file, so Validate /// never mutates the saved stack (wabil: Validate used to save first). content: Option, } /// POST /api/compose/stacks/{name}/validate — validate docker-compose.yml. /// /// If the editor posts its current content, validate that (via a throwaway file /// in the stack dir, so `.env` + relative paths still resolve) WITHOUT touching /// the saved compose file. With no body, validate the on-disk file (older UIs). async fn compose_validate( req: HttpRequest, state: web::Data, path: web::Path, body: Option>, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); if !dir.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let posted = body.and_then(|b| b.into_inner().content); let temp_file = dir.join(".wolfstack-validate.yml"); let file_str = match &posted { Some(content) => { if let Err(e) = std::fs::write(&temp_file, content) { return HttpResponse::InternalServerError() .json(serde_json::json!({ "error": format!("could not stage validation: {}", e) })); } temp_file.to_string_lossy().into_owned() } None => { let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } compose_file.to_string_lossy().into_owned() } }; let output = match crate::containers::compose_cmd() { Ok(mut c) => c .args(["-f", &file_str, "config", "--quiet"]) .envs(compose_secrets_env()) .current_dir(&dir) .output(), Err(e) => Err(std::io::Error::other(e)), }; // Remove the throwaway file regardless of the outcome — never leave it behind. if posted.is_some() { let _ = std::fs::remove_file(&temp_file); } match output { Ok(out) => { // `config` emits a warning per undefined ${VAR} on stderr even when // the YAML itself is valid (exit 0). Surface those so Validate also // catches "you referenced a variable that isn't set in .env / the // environment" — not just YAML syntax (wabil 2026-06-26). let stderr = String::from_utf8_lossy(&out.stderr).to_string(); let missing_vars = parse_undefined_compose_vars(&stderr); if out.status.success() { HttpResponse::Ok().json(serde_json::json!({ "valid": true, "missing_vars": missing_vars, })) } else { HttpResponse::Ok().json(serde_json::json!({ "valid": false, "error": stderr, "missing_vars": missing_vars, })) } } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": format!("{}", e) })), } } // ═══════════════════════════════════════════════════════════════════ // Secrets Manager // ═══════════════════════════════════════════════════════════════════ fn load_secrets() -> Vec { let path = std::path::Path::new(SECRETS_FILE); if !path.exists() { return Vec::new(); } std::fs::read_to_string(path) .ok() .and_then(|s| serde_json::from_str(&s).ok()) .unwrap_or_default() } /// True if `k` can be a POSIX environment-variable name — what `docker /// compose` can interpolate via `${k}`. Secrets with other names (spaces, /// dashes, leading digit) are skipped rather than passed as malformed env /// entries. fn is_valid_env_var_name(k: &str) -> bool { let mut chars = k.chars(); match chars.next() { Some(c) if c.is_ascii_alphabetic() || c == '_' => {} _ => return false, } chars.all(|c| c.is_ascii_alphanumeric() || c == '_') } /// Variables that change how the `docker` subprocess itself behaves rather /// than feed the stack. A secret with one of these names must never be /// injected — `PATH=` would strip the CLI's lookup path, `DOCKER_HOST` would /// redirect the daemon connection, `LD_PRELOAD` would inject a library into /// the docker client. Self-inflicted-only (the operator writes the store), /// but cheap to make impossible (code review 2026-06-10). const COMPOSE_ENV_DENYLIST: &[&str] = &[ "PATH", "HOME", "SHELL", "IFS", "LD_PRELOAD", "LD_LIBRARY_PATH", "DOCKER_HOST", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "DOCKER_CONFIG", "DOCKER_CONTEXT", "DOCKER_API_VERSION", "COMPOSE_FILE", "COMPOSE_PROJECT_NAME", "COMPOSE_PROFILES", ]; /// Environment pairs for `docker compose` subprocesses: every Secrets-Manager /// entry whose key is a valid env-var name (and not on the denylist above). /// Compose resolves `${KEY}` in the YAML (and `.env`-style references) from /// the process environment, so injecting the store here makes /// `environment: - DB_PASSWORD=${DB_PASSWORD}` work without ever writing the /// secret to disk next to the stack. Process env outranks the stack's `.env` /// file in compose's precedence, so a stale blank `KEY=` line in `.env` /// can't shadow a real secret. Secrets are per-node — a stack only sees the /// store of the node it runs on. Note a secret used via `environment:` ends /// up in the container's env like any other env var (visible to `docker /// inspect`) — inherent to env-var secrets, not to this injection. /// (Gary KO4BSR 2026-06-10: secrets referenced from compose came through /// blank because nothing ever injected them.) pub(crate) fn compose_secrets_env() -> Vec<(String, String)> { load_secrets() .into_iter() .filter(|s| is_injectable_secret_key(&s.key)) .map(|s| (s.key, s.value)) .collect() } /// Combined gate for `compose_secrets_env` — a valid env-var name that isn't /// a behaviour-altering variable. Split out so it's unit-testable without /// touching the on-disk store. fn is_injectable_secret_key(k: &str) -> bool { is_valid_env_var_name(k) && !COMPOSE_ENV_DENYLIST.contains(&k) } fn save_secrets(secrets: &[SecretEntry]) -> Result<(), String> { let dir = std::path::Path::new(SECRETS_FILE).parent().unwrap(); std::fs::create_dir_all(dir).map_err(|e| format!("{}", e))?; let json = serde_json::to_string_pretty(secrets).map_err(|e| format!("{}", e))?; // Atomic write: write to temp file with restricted permissions, then rename let tmp = format!("{}.tmp.{}.{}", SECRETS_FILE, std::process::id(), chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0)); std::fs::write(&tmp, &json).map_err(|e| format!("{}", e))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)); } std::fs::rename(&tmp, SECRETS_FILE).map_err(|e| { let _ = std::fs::remove_file(&tmp); format!("{}", e) })?; Ok(()) } fn now_iso() -> String { chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S").to_string() } /// GET /api/secrets — list all secrets (values masked) async fn secrets_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let secrets = load_secrets(); let masked: Vec = secrets.iter().map(|s| { let masked_val = if s.value.len() > 4 { format!("****{}", &s.value[s.value.len()-4..]) } else { "****".to_string() }; serde_json::json!({ "key": s.key, "value_masked": masked_val, "description": s.description, "created": s.created, "updated": s.updated, }) }).collect(); HttpResponse::Ok().json(serde_json::json!({ "secrets": masked })) } /// GET /api/secrets/{key} — get a single secret (full value) async fn secrets_get( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let key = path.into_inner(); let secrets = load_secrets(); match secrets.iter().find(|s| s.key == key) { Some(s) => HttpResponse::Ok().json(serde_json::json!({ "key": s.key, "value": s.value, "description": s.description, "created": s.created, "updated": s.updated, })), None => HttpResponse::NotFound().json(serde_json::json!({ "error": "Secret not found" })), } } /// POST /api/secrets — create or update a secret async fn secrets_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let key = body.key.trim().to_string(); if key.is_empty() { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Key is required" })); } let mut secrets = load_secrets(); let now = now_iso(); // Trim the value the same way we trim the key. A pasted credential or // token almost always carries a trailing newline (copied from a // terminal / password manager), which then gets injected into the // container verbatim — the value LOOKS correct everywhere it's shown but // downstream auth fails with no visible cause. `trim()` only touches // leading/trailing whitespace, so internal structure (e.g. multi-line // PEM bodies) is preserved. if let Some(existing) = secrets.iter_mut().find(|s| s.key == key) { if let Some(ref v) = body.value { existing.value = v.trim().to_string(); } if let Some(ref d) = body.description { existing.description = d.clone(); } existing.updated = now; } else { secrets.push(SecretEntry { key: key.clone(), value: body.value.as_deref().unwrap_or("").trim().to_string(), description: body.description.clone().unwrap_or_default(), created: now.clone(), updated: now, }); } match save_secrets(&secrets) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "Secret saved", "key": key })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// DELETE /api/secrets/{key} — delete a secret async fn secrets_delete( req: HttpRequest, state: web::Data, path: web::Path, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let key = path.into_inner(); let mut secrets = load_secrets(); let len = secrets.len(); secrets.retain(|s| s.key != key); if secrets.len() == len { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Secret not found" })); } match save_secrets(&secrets) { Ok(_) => HttpResponse::Ok().json(serde_json::json!({ "message": "Secret deleted" })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } // ─── Secrets export / import, stack deploy to a peer (Colt 2026-09-06) ─── #[derive(Deserialize)] struct SecretsExportRequest { passphrase: String, } /// POST /api/secrets/export — the whole Secrets Manager store as a /// passphrase-sealed file (Argon2id → AES-256-GCM, see `stack_transfer`). /// The config-export bundle deliberately excludes secrets because it is a /// hand-to-support artifact; this is the supported way to carry them to a /// standby or a rebuilt node. async fn secrets_export( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let passphrase = body.into_inner().passphrase; let sealed = web::block(move || { let secrets = load_secrets(); let plain = serde_json::to_vec(&secrets).map_err(|e| e.to_string())?; let host = hostname::get() .map(|h| h.to_string_lossy().to_string()) .unwrap_or_else(|_| "unknown".into()); crate::stack_transfer::seal_bundle(&plain, &passphrase, &host, secrets.len()) }).await; match sealed { Ok(Ok(bundle)) => { tracing::info!("secrets: exported {} entries as a passphrase-sealed bundle", bundle.count); let filename = format!( "wolfstack-secrets-{}-{}.json", bundle.exported_from, chrono::Utc::now().format("%Y%m%d-%H%M%S") ); HttpResponse::Ok() .insert_header(("Content-Disposition", format!("attachment; filename=\"{}\"", filename))) .json(bundle) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(Deserialize)] struct SecretsImportRequest { passphrase: String, bundle: crate::stack_transfer::SecretsBundle, /// Replace the value of a key that already exists here. Off by default: /// an import must not silently clobber a secret this host already runs /// with. #[serde(default)] overwrite: bool, } #[derive(Default, Serialize)] struct SecretsMergeOutcome { added: Vec, updated: Vec, unchanged: Vec, /// Existing keys left alone because `overwrite` was off. skipped: Vec, } /// Merge `incoming` into `existing`. Pure so the four outcomes are testable. fn merge_secrets(existing: &mut Vec, incoming: Vec, overwrite: bool) -> SecretsMergeOutcome { let now = now_iso(); let mut out = SecretsMergeOutcome::default(); for inc in incoming { let key = inc.key.trim().to_string(); if key.is_empty() { continue; } let value = inc.value.trim().to_string(); match existing.iter_mut().find(|s| s.key == key) { Some(cur) => { if cur.value == value && cur.description == inc.description { out.unchanged.push(key); } else if overwrite { cur.value = value; cur.description = inc.description; cur.updated = now.clone(); out.updated.push(key); } else { out.skipped.push(key); } } None => { existing.push(SecretEntry { key: key.clone(), value, description: inc.description, created: if inc.created.is_empty() { now.clone() } else { inc.created }, updated: now.clone(), }); out.added.push(key); } } } out } /// POST /api/secrets/import — open a bundle from `secrets_export` and merge it /// into this host's store. async fn secrets_import( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let b = body.into_inner(); let merged = web::block(move || -> Result { let plain = crate::stack_transfer::open_bundle(&b.bundle, &b.passphrase)?; let incoming: Vec = serde_json::from_slice(&plain) .map_err(|e| format!("bundle contents unreadable: {}", e))?; let mut secrets = load_secrets(); let outcome = merge_secrets(&mut secrets, incoming, b.overwrite); save_secrets(&secrets)?; Ok(outcome) }).await; match merged { Ok(Ok(o)) => { tracing::info!( "secrets: imported bundle — {} added, {} updated, {} unchanged, {} skipped", o.added.len(), o.updated.len(), o.unchanged.len(), o.skipped.len() ); let message = format!( "Imported: {} added, {} updated, {} already identical{}", o.added.len(), o.updated.len(), o.unchanged.len(), if o.skipped.is_empty() { String::new() } else { format!(", {} existing key(s) left unchanged (overwrite was off): {}", o.skipped.len(), o.skipped.join(", ")) } ); HttpResponse::Ok().json(serde_json::json!({ "message": message, "added": o.added, "updated": o.updated, "unchanged": o.unchanged, "skipped": o.skipped, })) } Ok(Err(e)) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } #[derive(Deserialize)] struct ComposeDeployRequest { node_id: String, /// Ship the Secrets Manager entries the compose file references. #[serde(default = "default_true")] include_secrets: bool, /// Run `up -d` on the peer once the files are in place. #[serde(default = "default_true")] start: bool, /// Replace a stack of the same name already on the peer. #[serde(default)] overwrite: bool, } /// Peer-to-peer payload for `/api/compose/receive`. #[derive(Serialize, Deserialize)] struct ComposeReceivePayload { name: String, files: Vec, secrets: Vec, start: bool, overwrite: bool, } /// POST /api/compose/stacks/{name}/deploy — copy this stack (its directory, /// bounded, plus the secrets it references) to another WolfStack node and /// optionally bring it up there. The half of a host failover no Proxmox /// feature reaches, because Proxmox does not know these containers exist. async fn compose_deploy( req: HttpRequest, state: web::Data, path: web::Path, body: web::Json, ) -> HttpResponse { if let Err(e) = require_auth(&req, &state) { return e; } let name = path.into_inner(); if let Err(e) = require_safe_compose_name(&name) { return e; } let dir = compose_project_dir(&name); let compose_file = compose_file_in(&dir); if !compose_file.exists() { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Stack not found" })); } let b = body.into_inner(); let Some(node) = state.cluster.get_node(&b.node_id) else { return HttpResponse::NotFound().json(serde_json::json!({ "error": "Target node not found" })); }; if node.is_self { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "The stack is already on this node — pick another target" })); } if node.node_type != "wolfstack" { return HttpResponse::BadRequest().json(serde_json::json!({ "error": "Only WolfStack nodes can receive a stack (a Proxmox node has no compose manager)" })); } if !node.online { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("{} is offline", node.hostname) })); } let include_secrets = b.include_secrets; let stack_name = name.clone(); let built = web::block(move || -> Result<(ComposeReceivePayload, Vec), String> { let (files, skipped) = crate::stack_transfer::collect_stack_files(&dir)?; let secrets = if include_secrets { let yaml = std::fs::read_to_string(&compose_file).map_err(|e| e.to_string())?; let refs = crate::stack_transfer::referenced_compose_vars(&yaml); load_secrets().into_iter() .filter(|s| refs.iter().any(|r| r == &s.key) && is_injectable_secret_key(&s.key)) .collect() } else { Vec::new() }; Ok((ComposeReceivePayload { name: stack_name, files, secrets, start: b.start, overwrite: b.overwrite }, skipped)) }).await; let (payload, skipped_files) = match built { Ok(Ok(v)) => v, Ok(Err(e)) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), }; let secrets_sent: Vec = payload.secrets.iter().map(|s| s.key.clone()).collect(); let file_count = payload.files.len(); // `up` on the peer may pull images: allow it the same fifteen minutes an // operator would wait at a terminal. The first URL that answers at all // is the answer — a 409 from the peer is a result, not a reason to try // the fallback port. let client = (*API_HTTP_CLIENT).clone(); let secret = state.cluster_secret.clone(); let self_id = state.cluster.self_id.clone(); let mut peer_reply: Option<(u16, serde_json::Value)> = None; for url in build_node_urls(&node.address, node.port, "/api/compose/receive") { let res = client.post(&url) .timeout(std::time::Duration::from_secs(900)) .peer_auth(&secret) .header("X-WolfStack-Node-Id", &self_id) .json(&payload) .send().await; if let Ok(resp) = res { let status = resp.status().as_u16(); let body = resp.json::().await .unwrap_or_else(|e| serde_json::json!({ "error": format!("unreadable reply from peer: {}", e) })); peer_reply = Some((status, body)); break; } } let Some((status, mut reply)) = peer_reply else { return HttpResponse::BadGateway().json(serde_json::json!({ "error": format!("{} did not answer on any of its API ports", node.hostname) })); }; if let Some(obj) = reply.as_object_mut() { obj.insert("target".into(), serde_json::Value::String(node.hostname.clone())); obj.insert("files_sent".into(), serde_json::json!(file_count)); obj.insert("secrets_sent".into(), serde_json::json!(secrets_sent)); obj.insert("skipped_files".into(), serde_json::json!(skipped_files)); } tracing::info!( "compose: deployed stack '{}' to {} ({} files, {} secrets, peer status {})", name, node.hostname, file_count, secrets_sent.len(), status ); match actix_web::http::StatusCode::from_u16(status) { Ok(code) => HttpResponse::build(code).json(reply), Err(_) => HttpResponse::BadGateway().json(reply), } } /// Write a received stack under the compose root, merge its secrets, and /// optionally bring it up. Blocking — runs inside `web::block`. fn apply_received_stack(p: ComposeReceivePayload) -> Result { use std::os::unix::fs::PermissionsExt; use base64::Engine; if !is_safe_compose_name(&p.name) { return Err(format!("invalid stack name {:?}", p.name)); } for f in &p.files { crate::stack_transfer::validate_relative_path(&f.path)?; } let compose_names = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"]; if !p.files.iter().any(|f| compose_names.contains(&f.path.as_str())) { return Err("payload carries no compose file at the stack root".into()); } let dir = compose_project_dir(&p.name); if compose_file_in(&dir).exists() && !p.overwrite { return Err(format!( "stack '{}' already exists on this node — deploy again with overwrite to replace its files", p.name )); } std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {}", dir.display(), e))?; for f in &p.files { let target = dir.join(&f.path); if let Some(parent) = target.parent() { std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {}", parent.display(), e))?; } let data = base64::engine::general_purpose::STANDARD.decode(&f.content) .map_err(|_| format!("{}: content is not valid base64", f.path))?; std::fs::write(&target, &data).map_err(|e| format!("write {}: {}", f.path, e))?; // `.env` may carry credentials: never wider than owner-only here, // whatever mode it had on the source. let mode = if f.path == ".env" { 0o600 } else { f.mode & 0o777 }; let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(mode)); } // The deploy's whole point is that the stack works here, so a secret the // source ships replaces a stale one of the same name. let mut secrets = load_secrets(); let merged = merge_secrets(&mut secrets, p.secrets, true); if !merged.added.is_empty() || !merged.updated.is_empty() { save_secrets(&secrets)?; } let mut report = if p.start { let out = run_compose_up(&dir)?; if !out.success { return Err(format!("files written, but `docker compose up` failed: {}", out.stderr.trim())); } compose_up_report(&out) } else { serde_json::json!({ "message": "Stack files written; not started" }) }; if let Some(obj) = report.as_object_mut() { obj.insert("files_written".into(), serde_json::json!(p.files.len())); obj.insert("secrets_added".into(), serde_json::json!(merged.added)); obj.insert("secrets_updated".into(), serde_json::json!(merged.updated)); obj.insert("started".into(), serde_json::json!(p.start)); } Ok(report) } /// POST /api/compose/receive — peer-to-peer target of `compose_deploy`. async fn compose_receive( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(e) = require_cluster_secret(&req, &state) { return e; } let sender = req.headers().get("X-WolfStack-Node-Id") .and_then(|v| v.to_str().ok()).unwrap_or("peer").to_string(); let p = body.into_inner(); let name = p.name.clone(); let (files, secrets) = (p.files.len(), p.secrets.len()); match web::block(move || apply_received_stack(p)).await { Ok(Ok(report)) => { tracing::info!( "compose: received stack '{}' from node {} ({} files, {} secrets)", name, sender, files, secrets ); HttpResponse::Ok().json(report) } Ok(Err(e)) => { tracing::warn!("compose: refused stack '{}' from node {}: {}", name, sender, e); if e.contains("already exists") { HttpResponse::Conflict().json(serde_json::json!({ "error": e })) } else { HttpResponse::BadRequest().json(serde_json::json!({ "error": e })) } } Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e.to_string() })), } } // ─── WolfNote Integration ─── /// POST /api/wolfnote/login — login to WolfNote and store the token #[derive(Deserialize)] pub struct WolfNoteLoginRequest { pub username: String, pub password: String, #[serde(default)] pub company: String, #[serde(default = "wolfnote_default_url")] pub url: String, } fn wolfnote_default_url() -> String { "https://app.wolfnote.org".to_string() } pub async fn wolfnote_login( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let base_url = if body.url.is_empty() { "https://app.wolfnote.org" } else { &body.url }; match crate::wolfnote::WolfNoteClient::login(base_url, &body.username, &body.password, &body.company).await { Ok(login_resp) => { // Save token and config let mut config = crate::wolfnote::WolfNoteConfig::load(); config.url = base_url.to_string(); config.token = login_resp.token; config.username = login_resp.user.username.clone(); config.company = body.company.clone(); if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "connected": true, "username": login_resp.user.username, })) } Err(e) => HttpResponse::Ok().json(serde_json::json!({ "connected": false, "error": e, })), } } /// POST /api/wolfnote/disconnect — clear the stored token pub async fn wolfnote_disconnect( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::wolfnote::WolfNoteConfig::load(); config.token.clear(); config.username.clear(); if let Err(e) = config.save() { return HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })); } HttpResponse::Ok().json(serde_json::json!({ "disconnected": true })) } /// GET /api/wolfnote/config — get current WolfNote config (token masked) pub async fn wolfnote_config_get( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfnote::WolfNoteConfig::load(); HttpResponse::Ok().json(serde_json::json!({ "url": config.url, "connected": config.is_connected(), "username": config.username, "company": config.company, "features": config.features, })) } /// POST /api/wolfnote/config — save feature toggles pub async fn wolfnote_config_save( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let mut config = crate::wolfnote::WolfNoteConfig::load(); if let Some(features) = body.get("features") && let Ok(f) = serde_json::from_value::(features.clone()) { config.features = f; } if let Some(url) = body.get("url").and_then(|v| v.as_str()) && !url.is_empty() { config.url = url.to_string(); } match config.save() { Ok(()) => HttpResponse::Ok().json(serde_json::json!({ "saved": true })), Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({ "error": e })), } } /// GET /api/wolfnote/folders — list folders from WolfNote pub async fn wolfnote_folders_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfnote::WolfNoteConfig::load(); if !config.is_connected() { return HttpResponse::Ok().json(serde_json::json!({ "error": "Not connected to WolfNote" })); } let client = crate::wolfnote::WolfNoteClient::new(&config.url, &config.token); match client.list_folders().await { Ok(folders) => HttpResponse::Ok().json(folders), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e })), } } /// POST /api/wolfnote/folders — create a folder in WolfNote #[derive(Deserialize)] pub struct WolfNoteCreateFolderRequest { pub name: String, #[serde(default)] pub parent_id: Option, #[serde(default)] pub color: Option, } pub async fn wolfnote_folders_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfnote::WolfNoteConfig::load(); if !config.is_connected() { return HttpResponse::Ok().json(serde_json::json!({ "error": "Not connected to WolfNote" })); } let client = crate::wolfnote::WolfNoteClient::new(&config.url, &config.token); match client.create_folder(&body.name, body.parent_id.as_deref(), body.color.as_deref()).await { Ok(folder) => HttpResponse::Ok().json(folder), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e })), } } /// GET /api/wolfnote/notes — list notes from WolfNote pub async fn wolfnote_notes_list( req: HttpRequest, state: web::Data, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfnote::WolfNoteConfig::load(); if !config.is_connected() { return HttpResponse::Ok().json(serde_json::json!({ "error": "Not connected to WolfNote" })); } let client = crate::wolfnote::WolfNoteClient::new(&config.url, &config.token); match client.list_notes().await { Ok(notes) => HttpResponse::Ok().json(notes), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e })), } } /// POST /api/wolfnote/notes — create a note in WolfNote #[derive(Deserialize)] pub struct WolfNoteCreateNoteRequest { pub title: String, #[serde(default)] pub content: String, #[serde(default)] pub folder_id: Option, } pub async fn wolfnote_notes_create( req: HttpRequest, state: web::Data, body: web::Json, ) -> HttpResponse { if let Err(resp) = require_auth(&req, &state) { return resp; } let config = crate::wolfnote::WolfNoteConfig::load(); if !config.is_connected() { return HttpResponse::Ok().json(serde_json::json!({ "error": "Not connected to WolfNote" })); } let client = crate::wolfnote::WolfNoteClient::new(&config.url, &config.token); match client.create_note(&body.title, &body.content, body.folder_id.as_deref()).await { Ok(note) => HttpResponse::Ok().json(note), Err(e) => HttpResponse::Ok().json(serde_json::json!({ "error": e })), } } // ─── Plugin System ─── /// GET /api/plugins — list all plugins. /// /// On Free installs the feature is gated, but plugins on disk are /// still listed so operators can see what would unlock with a Pro /// licence. We mask `has_css` / `has_frontend` to false in that case /// so the dashboard's asset loader doesn't fire ``/`