From 2446db612b30d83ee2ac6dfbae64be260ad61212 Mon Sep 17 00:00:00 2001 From: Stefan Steiner Date: Thu, 26 Nov 2026 11:12:20 -0800 Subject: [PATCH] fix(mcp): require a per-daemon token for STOP and REPORT_HYPERD_ERROR Each daemon start generates a random control token and publishes it in the owner-only daemon.json. STOP and REPORT_HYPERD_ERROR must carry it; otherwise the daemon answers ERR unauthorized and changes nothing. PING, HEARTBEAT and STATUS stay open, and the token never appears in STATUS, doctor output or logs. daemon.json and STATUS gain protocol_version (1). A takeover refused by a token-checking daemon fails at once with PermissionDenied. Phase S.1 of the hyperdb-daemon extraction design. --- Cargo.lock | 1 + hyperdb-mcp/CHANGELOG.md | 21 +++ hyperdb-mcp/Cargo.toml | 2 + hyperdb-mcp/src/daemon/discovery.rs | 209 +++++++++++++++++++++++++++- hyperdb-mcp/src/daemon/health.rs | 91 ++++++++++-- hyperdb-mcp/src/daemon/run.rs | 15 +- hyperdb-mcp/src/daemon/spawn.rs | 62 ++++++++- hyperdb-mcp/src/main.rs | 31 ++++- hyperdb-mcp/tests/daemon_tests.rs | 107 +++++++++++++- hyperdb-mcp/tests/doctor_tests.rs | 24 +++- 10 files changed, 534 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 754263de..b92b941e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1962,6 +1962,7 @@ dependencies = [ "notify", "parquet", "plotters", + "rand 0.10.3", "rmcp", "schemars", "semver", diff --git a/hyperdb-mcp/CHANGELOG.md b/hyperdb-mcp/CHANGELOG.md index b9e525f2..bc42e95a 100644 --- a/hyperdb-mcp/CHANGELOG.md +++ b/hyperdb-mcp/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Added +- **Control-token API for the daemon health protocol:** `ControlToken` + (`generate`, `as_str`, `matches`), `discovery::control_token_for` / + `control_token_in`, `health::authenticated_command`, + `health::UNAUTHORIZED_REPLY`, and `DaemonState::with_control_token` / + `control_token`. - **The npm platform packages now ship `THIRD-PARTY-LICENSES.txt`,** listing the licenses of the Rust crates linked into the `hyperdb-mcp` binary. It is generated at publish time with `cargo-about` (`about.toml`, `about.hbs`), and @@ -16,6 +21,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Changed +- **The daemon now requires a per-daemon control token on `STOP` and + `REPORT_HYPERD_ERROR`.** Each daemon start draws 32 random bytes from the OS + RNG and publishes them hex-encoded as `control_token` in the owner-only + `daemon.json`; clients read it from there and send `STOP ` / + `REPORT_HYPERD_ERROR `. A missing or wrong token gets `ERR + unauthorized` and changes nothing (a rejected report cannot trip the restart + limit). `PING`, `HEARTBEAT` and `STATUS` stay open, and the token is never in + `STATUS`, `doctor` output or logs. The record and `STATUS` also gain + `protocol_version` (`1`; absent means `0`). **Mixed versions:** upgrade every + hyperdb-mcp client together. A newer client talking to an older daemon (no + token in the record) sends the bare command as before; an older client + talking to this daemon gets `ERR unauthorized` on `STOP`, so it cannot stop + or take over the daemon, and its `REPORT_HYPERD_ERROR` is rejected too, so + it loses the fast restart and only the daemon's 5 s liveness poll remains. A + takeover refused this way fails at once with a `PermissionDenied` error + instead of waiting out the stop timeout. - **BREAKING (Rust API): `schema::map_hyper_type` now returns `Result`** instead of panicking on an out-of-range `NUMERIC`; callers must handle the error. - **`get_readme` is now written in a compact schema notation.** Tool diff --git a/hyperdb-mcp/Cargo.toml b/hyperdb-mcp/Cargo.toml index 6e2cd796..4eb2c775 100644 --- a/hyperdb-mcp/Cargo.toml +++ b/hyperdb-mcp/Cargo.toml @@ -44,6 +44,8 @@ tokio-util = { version = "0.7", features = ["rt"] } tempfile = { workspace = true } sqlformat = "0.5.0" dirs = "7" +# OS RNG for the per-daemon control token (workspace-pinned; already in the tree via hyperdb-api-core). +rand = { workspace = true } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/hyperdb-mcp/src/daemon/discovery.rs b/hyperdb-mcp/src/daemon/discovery.rs index 4c32e058..2833a0d8 100644 --- a/hyperdb-mcp/src/daemon/discovery.rs +++ b/hyperdb-mcp/src/daemon/discovery.rs @@ -44,12 +44,93 @@ pub(crate) struct DaemonBuildIdentity { executable_path: crate::diagnostics::ReportedPath, } +/// The health-protocol revision this build speaks and writes into `daemon.json` +/// and `STATUS`. A record that predates the field reads as `0`. Revision `1` +/// adds the per-daemon [`ControlToken`] on `STOP` and `REPORT_HYPERD_ERROR`. +pub(crate) const DAEMON_PROTOCOL_VERSION: u32 = 1; + +/// Per-daemon capability for the mutating health commands (`STOP`, +/// `REPORT_HYPERD_ERROR`): 32 bytes from the OS RNG, hex-encoded, fresh on +/// every daemon start. +/// +/// It lives in the owner-only `daemon.json` and is never served by `STATUS`. +/// `Debug` is redacted so a `{:?}` of a record, a state or an error cannot put +/// it in a log or a doctor report. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ControlToken(String); + +impl ControlToken { + /// Draw a fresh token from the operating system's RNG. + /// + /// # Errors + /// Returns an error if the OS RNG is unavailable; the daemon then refuses + /// to start rather than run with a guessable token. + pub fn generate() -> io::Result { + use rand::TryRng as _; + use std::fmt::Write as _; + + let mut bytes = [0_u8; 32]; + rand::rngs::SysRng + .try_fill_bytes(&mut bytes) + .map_err(|e| io::Error::other(format!("OS random number generator failed: {e}")))?; + let mut hex = String::with_capacity(bytes.len() * 2); + for byte in bytes { + write!(hex, "{byte:02x}").map_err(|e| io::Error::other(e.to_string()))?; + } + Ok(Self(hex)) + } + + /// The token as it is sent on the wire. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Constant-time comparison against a presented token. Only the length, + /// which is not secret, can end the comparison early. + #[must_use] + pub fn matches(&self, presented: &str) -> bool { + let (expected, presented) = (self.0.as_bytes(), presented.as_bytes()); + if expected.len() != presented.len() { + return false; + } + let difference = expected + .iter() + .zip(presented) + .fold(0_u8, |acc, (a, b)| acc | (a ^ b)); + std::hint::black_box(difference) == 0 + } +} + +impl std::fmt::Debug for ControlToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("ControlToken()") + } +} + +#[expect( + clippy::trivially_copy_pass_by_ref, + reason = "serde `skip_serializing_if` passes a reference" +)] +fn is_legacy_protocol(version: &u32) -> bool { + *version == 0 +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct DaemonRecord { #[serde(flatten)] info: DaemonInfo, #[serde(default, skip_serializing_if = "Option::is_none")] identity: Option, + /// Health-protocol revision; absent (an older daemon) reads as `0`, and `0` + /// is not written back, so a legacy record reserializes unchanged. + #[serde(default, skip_serializing_if = "is_legacy_protocol")] + protocol_version: u32, + /// Capability for `STOP` / `REPORT_HYPERD_ERROR`. Absent from `STATUS` + /// output and from records written by an older daemon. + #[serde(default, skip_serializing_if = "Option::is_none")] + control_token: Option, } impl DaemonRecord { @@ -63,9 +144,32 @@ impl DaemonRecord { executable.as_os_str(), ), }), + protocol_version: DAEMON_PROTOCOL_VERSION, + control_token: None, }) } + /// The record `STATUS` falls back to when the executable identity cannot + /// be collected: no identity, never a token, but still the protocol version. + pub(super) fn without_identity(info: &DaemonInfo) -> Self { + Self { + info: info.clone(), + identity: None, + protocol_version: DAEMON_PROTOCOL_VERSION, + control_token: None, + } + } + + #[cfg(test)] + pub(crate) fn protocol_version(&self) -> u32 { + self.protocol_version + } + + #[cfg(test)] + pub(crate) fn control_token(&self) -> Option<&ControlToken> { + self.control_token.as_ref() + } + pub(crate) fn info(&self) -> &DaemonInfo { &self.info } @@ -306,8 +410,13 @@ pub fn write_discovery_file_in(dir: &Path, info: &DaemonInfo) -> io::Result<()> /// Write the record with this process's identity, into `dir`. The daemon /// passes the state directory it already holds rather than re-reading the /// environment. -pub(super) fn write_enriched_discovery_file_in(dir: &Path, info: &DaemonInfo) -> io::Result<()> { - let record = DaemonRecord::with_current_identity(info)?; +pub(super) fn write_enriched_discovery_file_in( + dir: &Path, + info: &DaemonInfo, + control_token: &ControlToken, +) -> io::Result<()> { + let mut record = DaemonRecord::with_current_identity(info)?; + record.control_token = Some(control_token.clone()); write_discovery_record(dir, &record) } @@ -404,6 +513,40 @@ pub fn discover_in(dir: &Path) -> Option { } } +/// The control token the daemon serving `health` published in its record, or +/// `None` when the record carries none (a daemon older than protocol 1, which +/// takes the bare command) or cannot be read. +/// +/// The record is only believed if it names `health` as its endpoint, so a +/// token is never sent to an endpoint it was not issued for. +#[must_use] +pub fn control_token_for(health: &HealthEndpoint) -> Option { + control_token_in(&state_dir().ok()?, health) +} + +/// Whether two endpoint strings name the same endpoint. On Unix they are socket +/// paths and are compared as paths, as [`HealthEndpoint::from_record`] does. +fn same_endpoint(a: &str, b: &str) -> bool { + if cfg!(unix) { + Path::new(a) == Path::new(b) + } else { + a == b + } +} + +/// [`control_token_for`] for an explicit state directory. +#[must_use] +pub fn control_token_in(dir: &Path, health: &HealthEndpoint) -> Option { + match read_discovery_file_raw(&dir.join("daemon.json")) { + RawDiscoveryRead::Parsed { record, .. } + if same_endpoint(&record.info().health_endpoint, health.as_str()) => + { + record.control_token + } + _ => None, + } +} + /// Delete a daemon record that a dead daemon left behind. /// /// The caller must hold the [`DaemonLock`](super::lock::DaemonLock) for @@ -713,7 +856,8 @@ mod tests { "display": "/opt/hyperdb/bin/hyperdb-mcp", "encoding": "utf8" } - } + }, + "protocol_version": 1 }); let mut failures = Vec::new(); @@ -743,6 +887,8 @@ mod tests { let new_record = DaemonRecord { info: legacy_info(), identity: Some(identity.clone()), + protocol_version: DAEMON_PROTOCOL_VERSION, + control_token: None, }; match catch_serde(|| serde_json::to_value(&new_record)) { Ok(new_wire) => { @@ -1819,4 +1965,61 @@ mod tests { Some(legit_socket(dir.path())) ); } + + #[test] + fn control_token_is_64_hex_chars_fresh_each_time_and_redacted() { + let a = ControlToken::generate().unwrap(); + let b = ControlToken::generate().unwrap(); + assert_eq!(a.as_str().len(), 64); + assert!(a.as_str().bytes().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a, b); + assert!(!format!("{a:?}").contains(a.as_str())); + } + + #[test] + fn control_token_matches_only_the_exact_token() { + let token = ControlToken::generate().unwrap(); + assert!(token.matches(token.as_str())); + assert!(!token.matches("")); + assert!(!token.matches("wrong")); + assert!(!token.matches(&format!("{}0", token.as_str()))); + let mut flipped = token.as_str().to_string(); + flipped.replace_range(..1, if flipped.starts_with('a') { "b" } else { "a" }); + assert!(!token.matches(&flipped)); + } + + #[test] + fn record_without_token_or_protocol_version_parses_as_legacy() { + let wire = json!({ + "pid": 1, + "hyperd_endpoint": "127.0.0.1:1", + "health_endpoint": "/x.sock", + "started_at": "t", + "version": "0.7.0", + }); + let record: DaemonRecord = serde_json::from_value(wire).unwrap(); + assert_eq!(record.protocol_version(), 0); + assert!(record.control_token().is_none()); + } + + #[test] + fn written_record_carries_token_and_protocol_version_one() { + let dir = short_state_dir(); + let info = info_for(dir.path(), 4242); + let token = ControlToken::generate().unwrap(); + write_enriched_discovery_file_in(dir.path(), &info, &token).unwrap(); + + let raw: Value = + serde_json::from_slice(&std::fs::read(dir.path().join("daemon.json")).unwrap()) + .unwrap(); + assert_eq!(raw["protocol_version"], 1); + assert_eq!(raw["control_token"], token.as_str()); + + let endpoint = HealthEndpoint::from_record(&info.health_endpoint, dir.path()).unwrap(); + assert_eq!(control_token_in(dir.path(), &endpoint), Some(token)); + // A record is not believed for an endpoint it does not name. + let other = short_state_dir(); + let other_endpoint = HealthEndpoint::for_new_daemon(other.path()).unwrap(); + assert_eq!(control_token_in(dir.path(), &other_endpoint), None); + } } diff --git a/hyperdb-mcp/src/daemon/health.rs b/hyperdb-mcp/src/daemon/health.rs index 2b23b344..86746597 100644 --- a/hyperdb-mcp/src/daemon/health.rs +++ b/hyperdb-mcp/src/daemon/health.rs @@ -21,11 +21,17 @@ //! token proves it's a hyperdb-mcp daemon, not some other program that //! happens to answer on the endpoint) //! - `HEARTBEAT\n` -> `OK\n` (resets idle timer) -//! - `STOP\n` -> `STOPPING\n` (triggers graceful shutdown) +//! - `STOP \n` -> `STOPPING\n` (triggers graceful shutdown) //! - `STATUS\n` -> JSON line with daemon info (reports the *current* hyperd //! endpoint, which can change after a restart). -//! - `REPORT_HYPERD_ERROR\n` -> `OK\n` (sets the restart-requested flag -- -//! the monitor task picks it up on its next tick). +//! - `REPORT_HYPERD_ERROR \n` -> `OK\n` (sets the restart-requested +//! flag -- the monitor task picks it up on its next tick). +//! +//! `STOP` and `REPORT_HYPERD_ERROR` carry the daemon's [`ControlToken`], read +//! from the owner-only `daemon.json`; a missing or wrong token gets +//! `ERR unauthorized` and changes nothing. `PING`, `HEARTBEAT` and `STATUS` +//! stay open. A daemon whose record has no token (older than protocol 1) is +//! sent the bare command. //! //! Known limits, accepted because only the owning user can reach the channel: //! the server does not bound the length of a request line or the number of @@ -39,7 +45,7 @@ use std::time::{Duration, Instant}; use tracing::{debug, warn}; use super::control::{self, CONNECTION_IO_TIMEOUT, ControlListener, ControlStream, HealthEndpoint}; -use super::discovery::{DaemonInfo, DaemonRecord}; +use super::discovery::{self, ControlToken, DaemonInfo, DaemonRecord}; /// Identifying token included in PONG responses. Used to verify that an /// endpoint is served by a hyperdb-mcp daemon (not some other program). @@ -59,6 +65,9 @@ pub const PONG_TOKEN: &str = "hyperdb-mcp"; /// costing only one wakeup per second (see issue #274 for the measurements). const ACCEPT_POLL_INTERVAL: Duration = Duration::from_secs(1); +/// The reply to `STOP` or `REPORT_HYPERD_ERROR` without a valid control token. +pub const UNAUTHORIZED_REPLY: &str = "ERR unauthorized"; + /// Construct the PONG response with the identifying token and version. fn pong_response() -> String { format!("PONG {PONG_TOKEN} {}\n", crate::version::MCP_VERSION) @@ -107,12 +116,30 @@ pub struct DaemonState { /// poll of the `hyperd` monitor (every 5 s). `notify_one` stores a permit, /// so a request that lands before the loop first awaits is not lost. shutdown_notify: tokio::sync::Notify, + /// Capability a client must present on `STOP` and `REPORT_HYPERD_ERROR`. + /// Drawn once per state; the daemon publishes it in `daemon.json`. + control_token: ControlToken, } impl DaemonState { /// A fresh state for a daemon whose health listener is (or will be) bound /// at `endpoint`. + /// + /// Convenience for tests and tools. `run_daemon` does not use it: it draws + /// the token itself and passes it to [`Self::with_control_token`] so an RNG + /// failure is an error, not a panic. + /// + /// # Panics + /// Panics if the OS random number generator fails. pub fn new(endpoint: HealthEndpoint) -> Self { + Self::with_control_token( + endpoint, + ControlToken::generate().expect("OS random number generator unavailable"), + ) + } + + /// [`Self::new`] with a caller-supplied control token. + pub fn with_control_token(endpoint: HealthEndpoint, control_token: ControlToken) -> Self { Self { last_activity: Mutex::new(Instant::now()), shutdown: AtomicBool::new(false), @@ -120,9 +147,15 @@ impl DaemonState { endpoint, listener_registered: AtomicBool::new(false), shutdown_notify: tokio::sync::Notify::new(), + control_token, } } + /// The token this daemon requires on its mutating commands. + pub fn control_token(&self) -> &ControlToken { + &self.control_token + } + /// Record activity (resets idle timer). /// /// # Panics @@ -371,7 +404,7 @@ fn status_json(info: &Mutex) -> String { Ok(record) => serde_json::to_string(&record).unwrap_or_default(), Err(error) => { warn!(%error, "could not collect daemon executable identity for STATUS"); - serde_json::to_string(&snapshot).unwrap_or_default() + serde_json::to_string(&DaemonRecord::without_identity(&snapshot)).unwrap_or_default() } } } @@ -388,8 +421,31 @@ fn handle_client(mut stream: ControlStream, state: &DaemonState, info: &Mutex break, Ok(_) => { - let cmd = line.trim(); + let line = line.trim(); + let (cmd, presented) = match line.split_once(char::is_whitespace) { + Some((cmd, rest)) => (cmd, Some(rest.trim())), + None => (line, None), + }; + // Only the two mutating verbs take an argument; anything else + // with trailing text is an unknown command, as before. + let cmd = if presented.is_some() && !matches!(cmd, "STOP" | "REPORT_HYPERD_ERROR") { + line + } else { + cmd + }; + let authorized = + || presented.is_some_and(|token| state.control_token.matches(token)); let response = match cmd { + "STOP" | "REPORT_HYPERD_ERROR" if !authorized() => { + warn!( + command = cmd, + "rejected a health command without a valid control token; the \ + client is either older than this daemon (upgrade all hyperdb-mcp \ + clients together) or read a missing, stale or overwritten \ + daemon.json" + ); + format!("{UNAUTHORIZED_REPLY}\n") + } "PING" => pong_response(), "HEARTBEAT" => { state.touch(); @@ -417,6 +473,17 @@ fn handle_client(mut stream: ControlStream, state: &DaemonState, info: &Mutex) -> String { + match token { + Some(token) => format!("{verb} {}", token.as_str()), + None => verb.to_string(), + } +} + /// Send a command to the daemon's health endpoint and return the response. /// /// Uses generous timeouts (2s connect, 5s read) suitable for `STOP`/`STATUS` @@ -440,7 +507,11 @@ pub fn send_command(endpoint: &HealthEndpoint, command: &str) -> std::io::Result /// Errors are logged at debug level and otherwise ignored. pub fn report_hyperd_error_to_daemon(endpoint: &HealthEndpoint) { let timeout = Duration::from_millis(200); - match send_command_with_timeout(endpoint, "REPORT_HYPERD_ERROR", timeout, timeout) { + let command = authenticated_command( + "REPORT_HYPERD_ERROR", + discovery::control_token_for(endpoint).as_ref(), + ); + match send_command_with_timeout(endpoint, &command, timeout, timeout) { Ok(response) => { debug!(response = %response.trim(), "reported hyperd error to daemon"); } @@ -732,7 +803,8 @@ mod tests { "identity": { "mcp_version": crate::version::mcp_version_string(), "executable_path": executable_path - } + }, + "protocol_version": 1 }) } @@ -805,7 +877,8 @@ mod tests { &mut failures, ); - let _ = send_command(&endpoint, "STOP"); + let stop = authenticated_command("STOP", Some(state.control_token())); + let _ = send_command(&endpoint, &stop); handle.join().unwrap(); assert!( diff --git a/hyperdb-mcp/src/daemon/run.rs b/hyperdb-mcp/src/daemon/run.rs index aaf66955..13c4950f 100644 --- a/hyperdb-mcp/src/daemon/run.rs +++ b/hyperdb-mcp/src/daemon/run.rs @@ -201,14 +201,20 @@ pub async fn run_daemon(config: DaemonConfig) -> Result<(), Box { info!(endpoint = %new_endpoint, "hyperd restarted"); // Drain any reports that landed *during* the restart — those @@ -454,6 +460,7 @@ fn try_restart_hyperd( hyper_state: &Mutex, info_arc: &Mutex, state_dir: &Path, + control_token: &discovery::ControlToken, ) -> Result { let mut guard = hyper_state.lock().expect("HyperState mutex poisoned"); @@ -514,7 +521,7 @@ fn try_restart_hyperd( let mut info_guard = info_arc.lock().expect("DaemonInfo mutex poisoned"); let mut snapshot = info_guard.clone(); snapshot.hyperd_endpoint.clone_from(&new_endpoint); - discovery::write_enriched_discovery_file_in(state_dir, &snapshot) + discovery::write_enriched_discovery_file_in(state_dir, &snapshot, control_token) .map_err(|e| RestartError::SpawnFailed(format!("discovery write: {e}")))?; info_guard.hyperd_endpoint.clone_from(&new_endpoint); } diff --git a/hyperdb-mcp/src/daemon/spawn.rs b/hyperdb-mcp/src/daemon/spawn.rs index 8ecc55d0..b0c1c0d5 100644 --- a/hyperdb-mcp/src/daemon/spawn.rs +++ b/hyperdb-mcp/src/daemon/spawn.rs @@ -332,7 +332,28 @@ fn maybe_take_over( }; // Send STOP (best-effort; ignore error if daemon is already dying). - let _ = super::health::send_command(&endpoint, "STOP"); + // A record without a token is an older daemon, which takes the bare + // command. A token-checking daemon answers `ERR unauthorized` when the + // token is missing or wrong; waiting the full `stop_wait` for a daemon that + // was told no would only stall the caller, so fail at once. + let stop = super::health::authenticated_command( + "STOP", + discovery::control_token_in(dir, &endpoint).as_ref(), + ); + if let Ok(reply) = super::health::send_command(&endpoint, &stop) + && reply.trim() == super::health::UNAUTHORIZED_REPLY + { + warn!( + endpoint = %info.health_endpoint, + "old daemon refused STOP, not taking over" + ); + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "the running daemon refused STOP: the control token was unavailable or rejected \ + (daemon.json missing, stale or overwritten -- for instance by a pre-1.0 daemon -- \ + or this client is older than the daemon)", + )); + } // Wait for the old daemon to let go of the lock. if let Err(error) = wait_for_lock_release(dir, stop_wait) { @@ -876,9 +897,11 @@ mod tests { version: "0.0.1".to_string(), }; let record = dir.join("daemon.json"); - std::fs::write(&record, serde_json::to_vec(&info).expect("serialize")).expect("write"); - + // Like a real daemon, publish the control token with the record: + // the takeover's STOP is only honored if it reads and sends it. let state = Arc::new(DaemonState::new(endpoint)); + discovery::write_enriched_discovery_file_in(dir, &info, state.control_token()) + .expect("write record"); let quit = Arc::new(AtomicBool::new(false)); let listener_state = Arc::clone(&state); let listener_thread = std::thread::spawn(move || { @@ -957,6 +980,39 @@ mod tests { assert!(started.elapsed() >= Duration::from_millis(500)); } + /// A daemon that answers `STOP` with `ERR unauthorized` (here: the record + /// holds a stale token) must fail the takeover at once with a + /// `PermissionDenied` error, not after the full `STOP` wait, and never + /// spawn. + #[test] + fn takeover_fails_fast_when_the_daemon_refuses_stop() { + let dir = tempfile::tempdir().expect("state dir"); + let _old = FakeOldDaemon::start(dir.path(), None); + let info = discovery::discover_in(dir.path()).expect("fake daemon is discoverable"); + let stale = discovery::ControlToken::generate().expect("token"); + discovery::write_enriched_discovery_file_in(dir.path(), &info, &stale) + .expect("overwrite record with a stale token"); + let calls = Cell::new(0); + let started = Instant::now(); + + let error = ensure_daemon_in( + dir.path(), + counting_spawner(&calls), + Duration::from_millis(200), + Duration::from_secs(10), + ) + .expect_err("a refused STOP must not end in a takeover"); + + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert!(error.to_string().contains("control token"), "{error}"); + assert!( + started.elapsed() < Duration::from_secs(5), + "took {:?}, it must not wait out the STOP wait", + started.elapsed() + ); + assert_eq!(calls.get(), 0, "the spawner must never run"); + } + /// An old daemon that never releases the lock: no spawn, a `TimedOut` /// error (the caller runs in local mode). #[test] diff --git a/hyperdb-mcp/src/main.rs b/hyperdb-mcp/src/main.rs index 893aa277..55d105a4 100644 --- a/hyperdb-mcp/src/main.rs +++ b/hyperdb-mcp/src/main.rs @@ -369,7 +369,36 @@ fn running_daemon_endpoint() -> daemon::control::HealthEndpoint { fn daemon_stop() { let endpoint = running_daemon_endpoint(); - match health::send_command(&endpoint, "STOP") { + let token = discovery::control_token_for(&endpoint); + let stop = health::authenticated_command("STOP", token.as_ref()); + match health::send_command(&endpoint, &stop) { + Ok(response) if response.trim() == health::UNAUTHORIZED_REPLY => { + if token.is_some() { + eprintln!( + "The daemon refused STOP: it rejected the control token in daemon.json. \ + The record may be stale or overwritten, or this client is older than the \ + daemon (upgrade every hyperdb-mcp client to the same version)." + ); + } else { + // No token was found, so there was nothing to present. Give the + // user a way out: the PID, from the daemon's own STATUS. + let pid = health::send_command(&endpoint, "STATUS") + .ok() + .and_then(|reply| { + serde_json::from_str::(reply.trim()).ok() + }) + .map(|info| info.pid); + eprintln!( + "The daemon requires a control token, but none was found in daemon.json \ + (missing, unreadable or written by an older daemon), so STOP was refused." + ); + match pid { + Some(pid) => eprintln!("Stop it manually: the daemon's process ID is {pid}."), + None => eprintln!("Its process ID could not be read from STATUS."), + } + } + std::process::exit(1); + } Ok(response) => { println!("Daemon responded: {}", response.trim()); } diff --git a/hyperdb-mcp/tests/daemon_tests.rs b/hyperdb-mcp/tests/daemon_tests.rs index 782f5cb0..173bc3f6 100644 --- a/hyperdb-mcp/tests/daemon_tests.rs +++ b/hyperdb-mcp/tests/daemon_tests.rs @@ -69,6 +69,12 @@ fn acquire_env_lock() -> std::sync::MutexGuard<'static, ()> { .unwrap_or_else(std::sync::PoisonError::into_inner) } +/// `verb` with the control token the daemon in `dir` published in its record, +/// as a real client sends it. +fn with_recorded_token(verb: &str, dir: &Path, endpoint: &HealthEndpoint) -> String { + health::authenticated_command(verb, discovery::control_token_in(dir, endpoint).as_ref()) +} + // ─── Unit tests: DaemonState (no env vars, safe to run in parallel) ─────────── /// A `DaemonState` for a daemon whose endpoint lives in a fresh state @@ -434,7 +440,8 @@ fn health_protocol_stop_triggers_shutdown() { assert!(!health.state.should_shutdown()); - let response = health::send_command(&health.endpoint, "STOP").unwrap(); + let stop = health::authenticated_command("STOP", Some(health.state.control_token())); + let response = health::send_command(&health.endpoint, &stop).unwrap(); assert_eq!(response.trim(), "STOPPING"); assert!(health.state.should_shutdown()); @@ -443,6 +450,41 @@ fn health_protocol_stop_triggers_shutdown() { health.join(); } +#[test] +fn health_protocol_stop_without_or_with_wrong_token_is_rejected() { + let (_dir, mut health) = start_health_listener(); + + for command in ["STOP", "STOP wrong-token", "STOP "] { + let response = health::send_command(&health.endpoint, command).unwrap(); + assert_eq!(response.trim(), "ERR unauthorized", "command {command:?}"); + } + assert!( + !health.state.should_shutdown(), + "a rejected STOP must not shut the daemon down" + ); + + // The daemon is still serving, and the right token still works. + let stop = health::authenticated_command("STOP", Some(health.state.control_token())); + assert_eq!( + health::send_command(&health.endpoint, &stop) + .unwrap() + .trim(), + "STOPPING" + ); + health.join(); +} + +#[test] +fn health_protocol_status_never_contains_the_token() { + let (_dir, health) = start_health_listener(); + + let response = health::send_command(&health.endpoint, "STATUS").unwrap(); + assert!(!response.contains(health.state.control_token().as_str())); + let parsed: serde_json::Value = serde_json::from_str(response.trim()).unwrap(); + assert!(parsed.get("control_token").is_none()); + assert_eq!(parsed["protocol_version"], 1); +} + #[test] fn health_protocol_status_returns_json() { let (_dir, health) = start_health_listener(); @@ -467,7 +509,9 @@ fn health_protocol_report_hyperd_error_sets_flag() { assert!(!health.state.consume_restart_request(), "flag starts clear"); - let response = health::send_command(&health.endpoint, "REPORT_HYPERD_ERROR").unwrap(); + let report = + health::authenticated_command("REPORT_HYPERD_ERROR", Some(health.state.control_token())); + let response = health::send_command(&health.endpoint, &report).unwrap(); assert_eq!(response.trim(), "OK"); // The handler ran on a different thread. The flag is set before the OK @@ -478,6 +522,27 @@ fn health_protocol_report_hyperd_error_sets_flag() { ); } +#[test] +fn health_protocol_unauthorized_reports_never_set_the_restart_flag() { + let (_dir, health) = start_health_listener(); + + // The restart flag is the only path from a report to a restart (and so to + // `RESTART_LIMIT`). More than `RESTART_LIMIT` rejected reports must leave + // it clear. + for command in ["REPORT_HYPERD_ERROR", "REPORT_HYPERD_ERROR nope"] + .into_iter() + .cycle() + .take(hyperdb_mcp::daemon::run::RESTART_LIMIT + 1) + { + let response = health::send_command(&health.endpoint, command).unwrap(); + assert_eq!(response.trim(), "ERR unauthorized", "command {command:?}"); + } + assert!( + !health.state.consume_restart_request(), + "a rejected report must not request a restart" + ); +} + #[test] fn health_protocol_multi_command_session() { let (_dir, health) = start_health_listener(); @@ -711,6 +776,16 @@ fn run_engine_report_child() { .expect("daemon info mutex must not be poisoned") .clone(); discovery::write_discovery_file(&daemon_info).expect("write isolated daemon discovery record"); + // A real daemon publishes its control token with the record; the report is + // only honored when the client reads and sends it. + let mut record = serde_json::to_value(&daemon_info).expect("record as JSON"); + record["protocol_version"] = serde_json::Value::from(1); + record["control_token"] = serde_json::Value::from(health.state.control_token().as_str()); + std::fs::write( + discovery::discovery_file_path().expect("discovery file path"), + serde_json::to_vec(&record).expect("serialize record"), + ) + .expect("rewrite discovery record with the control token"); assert!( !health.state.consume_restart_request(), "restart flag must begin clear" @@ -1795,7 +1870,11 @@ fn client_report_triggers_restart_after_kill() { // Even so, the monitor only reacts on its 5s tick, so the worst-case // recovery time is unchanged. This test just verifies the report path // triggers the same restart as detection-via-polling. - let response = health::send_command(&daemon.endpoint, "REPORT_HYPERD_ERROR").unwrap(); + let response = health::send_command( + &daemon.endpoint, + &with_recorded_token("REPORT_HYPERD_ERROR", &daemon.state_dir, &daemon.endpoint), + ) + .unwrap(); assert_eq!(response.trim(), "OK"); let new_endpoint = wait_for_live_hyperd_after_kill( @@ -2399,7 +2478,10 @@ impl TestDaemon { impl Drop for TestDaemon { fn drop(&mut self) { - let _ = health::send_command(&self.endpoint, "STOP"); + let _ = health::send_command( + &self.endpoint, + &with_recorded_token("STOP", &self.state_dir, &self.endpoint), + ); // The daemon holds the state directory's lock until after its `hyperd` // has exited, so the lock being free is the one reliable sign of full // shutdown (`HyperProcess` drop can take ~5s). Waiting on the control @@ -2635,7 +2717,11 @@ fn a_daemon_started_right_after_stop_takes_over_the_state_directory() { let bound = Duration::from_secs(3); let exit_bound = Duration::from_secs(15); let started = Instant::now(); - let response = health::send_command(&endpoint, "STOP").expect("STOP reaches daemon A"); + let response = health::send_command( + &endpoint, + &with_recorded_token("STOP", &state_dir, &endpoint), + ) + .expect("STOP reaches daemon A"); assert_eq!(response.trim(), "STOPPING"); let daemon_b = spawn_daemon_thread(); @@ -2675,7 +2761,10 @@ fn a_daemon_started_right_after_stop_takes_over_the_state_directory() { // Tear B down and wait for its lock, as TestDaemon does. let endpoint_b = HealthEndpoint::from_record(&info_b.health_endpoint, &state_dir).unwrap(); - let _ = health::send_command(&endpoint_b, "STOP"); + let _ = health::send_command( + &endpoint_b, + &with_recorded_token("STOP", &state_dir, &endpoint_b), + ); hyperdb_mcp::daemon::spawn::wait_for_lock_release(&state_dir, Duration::from_secs(15)) .expect("daemon B releases the lock after STOP"); daemon_b @@ -2699,7 +2788,11 @@ fn stop_removes_the_daemon_record_promptly() { assert!(record.exists(), "a running daemon has a record"); let sent = Instant::now(); - health::send_command(&daemon.endpoint, "STOP").expect("STOP reaches the daemon"); + health::send_command( + &daemon.endpoint, + &with_recorded_token("STOP", &daemon.state_dir, &daemon.endpoint), + ) + .expect("STOP reaches the daemon"); while record.exists() { assert!( sent.elapsed() < Duration::from_secs(1), diff --git a/hyperdb-mcp/tests/doctor_tests.rs b/hyperdb-mcp/tests/doctor_tests.rs index bd941a19..f0569974 100644 --- a/hyperdb-mcp/tests/doctor_tests.rs +++ b/hyperdb-mcp/tests/doctor_tests.rs @@ -2031,8 +2031,14 @@ fn doctor_cli_reports_live_from_discovery_via_real_health_listener() { let listener = RunningHealthListener::start(&sandbox); let discovery_path = sandbox.state_dir.join("daemon.json"); + // The record carries the control token; the doctor must read it + // without ever echoing it. + let token = listener.state.control_token().as_str().to_owned(); + let mut fixture = serde_json::to_value(&listener.info).expect("fixture value"); + fixture["protocol_version"] = Value::from(1); + fixture["control_token"] = Value::from(token.clone()); let discovery_bytes = - serde_json::to_vec_pretty(&listener.info).expect("serialize discovery fixture"); + serde_json::to_vec_pretty(&fixture).expect("serialize discovery fixture"); std::fs::write(&discovery_path, &discovery_bytes).expect("write discovery fixture"); let before = snapshot_tree(&sandbox.root); @@ -2043,6 +2049,13 @@ fn doctor_cli_reports_live_from_discovery_via_real_health_listener() { &launcher_metadata, Some(missing_hyperd.as_os_str()), ); + if String::from_utf8_lossy(&output.stdout).contains(&token) + || String::from_utf8_lossy(&output.stderr).contains(&token) + { + failures.push(format!( + "attempt {attempt}: doctor --json leaked the control token" + )); + } let report = parse_json_report( &output, "hyperdb-mcp doctor --json against discovery HealthListener", @@ -2073,6 +2086,11 @@ fn doctor_cli_reports_live_from_discovery_via_real_health_listener() { ); let human = std::str::from_utf8(&human_output.stdout) .expect("live-daemon human report must be UTF-8"); + if human.contains(&token) { + failures.push(format!( + "attempt {attempt}: doctor leaked the control token" + )); + } if let Some(failure) = live_daemon_human_parity_failure(&report, human) { failures.push(format!( "attempt {attempt}: live JSON/human identity parity: {failure}" @@ -2087,7 +2105,9 @@ fn doctor_cli_reports_live_from_discovery_via_real_health_listener() { match std::fs::read(&discovery_path) { Ok(after) if after == discovery_bytes => {} Ok(after) => failures.push(format!( - "attempt {attempt}: discovery bytes changed: before={discovery_bytes:?}, after={after:?}" + "attempt {attempt}: discovery bytes changed ({} bytes before, {} after; not printed: they hold the control token)", + discovery_bytes.len(), + after.len() )), Err(error) => failures.push(format!( "attempt {attempt}: discovery fixture disappeared: {error}"