AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(server): fail closed when TLS is requested but cannot be established
xerj-org52667389ad85
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex baf98e0ab..69fc35445 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -1596,11 +1596,21 @@ async fn async_main() -> Result<()> {// 5. Admin key (first-run)ensure_admin_key(&mut cfg)?;- // 6. TLS certificate- if let Err(e) = ensure_tls_cert(&mut cfg) {- error!("TLS setup failed ({e:#}) — falling back to plain HTTP");- cfg.tls.enabled = false;- }+ // 6. TLS certificate — fail closed (issue #200). The operator asked for+ // TLS; if the certificate step cannot deliver it, refuse to start+ // rather than bind the same ports in cleartext. A downgrade is+ // invisible to every working client — the only signal is one log+ // line — while API keys cross a wire the operator believes is+ // encrypted. `Config::validate` has already rejected+ // `tls.enabled = true` with empty cert/key paths at load time, so an+ // error here means reusing or auto-generating the certificate+ // genuinely failed (unwritable data dir, obstructed target, …), and+ // a config that never went through `validate` (defaults) has TLS off.+ ensure_tls_cert(&mut cfg).context(+ "tls.enabled = true but TLS could not be established; refusing to \+ start rather than serve plain HTTP — fix the certificate setup, or \+ disable TLS explicitly (tls.enabled = false, or --insecure for dev)",+ )?;// 6b. In-process TLS config (rustls). Loaded once here and shared// (cheap Arc clone) by both listeners. When TLS is enabled but the@@ -2063,6 +2073,48 @@ mod tls_tests {"missing cert with TLS enabled must error, not downgrade");}++ /// Issue #200: a failure inside the certificate step must surface as an+ /// error with `tls.enabled` left ON, so the caller (`async_main`) aborts+ /// startup. Before the fix the call site swallowed the error and flipped+ /// `tls.enabled = false`, downgrading an operator-requested HTTPS+ /// listener to cleartext on the same ports.+ ///+ /// Scenario: `Config::validate` rejects `tls.enabled = true` with empty+ /// paths outright, so the reachable failure shape is non-empty cert/key+ /// paths whose files are missing (→ the auto-generation branch) with the+ /// generation target obstructed. A directory squatting on+ /// `<data_dir>/xerj.crt` makes the cert write fail deterministically on+ /// every platform, for root too.+ #[test]+ fn ensure_tls_cert_failure_errors_without_downgrading() {+ let dir = tempfile::tempdir().unwrap();+ let mut cfg = Config::default();+ cfg.server.data_dir = dir.path().to_string_lossy().into_owned();+ cfg.tls.enabled = true;+ cfg.tls.cert_path = dir+ .path()+ .join("missing.crt")+ .to_string_lossy()+ .into_owned();+ cfg.tls.key_path = dir+ .path()+ .join("missing.key")+ .to_string_lossy()+ .into_owned();+ std::fs::create_dir_all(dir.path().join("xerj.crt")).unwrap();++ let res = ensure_tls_cert(&mut cfg);+ assert!(+ res.is_err(),+ "an obstructed cert auto-generation target must error"+ );+ assert!(+ cfg.tls.enabled,+ "a TLS setup failure must never flip tls.enabled off — \+ fail closed, not fail open"+ );+ }}/// RC4 W2 #20/#21 regression tests. Like `tls_tests` above, these live indiff --git a/engine/crates/xerj-server/tests/tls_fail_closed.rs b/engine/crates/xerj-server/tests/tls_fail_closed.rsnew file mode 100644index 000000000..f85ec23b6--- /dev/null+++ b/engine/crates/xerj-server/tests/tls_fail_closed.rs@@ -0,0 +1,117 @@+//! Issue #200: TLS must fail closed at startup.+//!+//! With `tls.enabled = true` and a certificate step that cannot deliver, the+//! REAL binary must exit non-zero before binding anything — never log the+//! failure and serve the same ports as cleartext HTTP. The pre-fix behavior+//! (downgrade + serve forever) makes every client keep working, which is+//! exactly why nobody notices; this test would then hit its deadline and+//! fail rather than hang.+//!+//! Failure shape: `Config::validate` rejects empty cert/key paths at load+//! time, so the reachable in-production failure is non-empty paths whose+//! files are missing — that routes `ensure_tls_cert` into self-signed+//! auto-generation targeting `<data_dir>/xerj.crt`, which a squatting+//! directory makes fail deterministically on every platform, for root too.++use std::io::Read;+use std::net::TcpListener;+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++/// Three distinct free ports, held simultaneously so they cannot collide,+/// then released for the child. `Config::validate` requires all three+/// listener ports to differ; free ports also mean that a regressed+/// (downgrading) binary binds cleanly and keeps serving instead of dying on+/// an unrelated bind error — which would masquerade as a pass.+fn three_free_ports() -> (u16, u16, u16) {+ let l1 = TcpListener::bind("127.0.0.1:0").unwrap();+ let l2 = TcpListener::bind("127.0.0.1:0").unwrap();+ let l3 = TcpListener::bind("127.0.0.1:0").unwrap();+ (+ l1.local_addr().unwrap().port(),+ l2.local_addr().unwrap().port(),+ l3.local_addr().unwrap().port(),+ )+}++/// TOML-safe rendering of a temp path (Windows backslashes would be escape+/// sequences inside a basic string; forward slashes work on every platform).+fn toml_path(p: &std::path::Path) -> String {+ p.to_string_lossy().replace('\\', "/")+}++#[test]+fn tls_failure_refuses_to_start_instead_of_downgrading() {+ let dir = tempfile::tempdir().unwrap();+ let data_dir = dir.path().join("data");+ // Obstruct the auto-generation target: `<data_dir>/xerj.crt` is a+ // directory, so writing the generated certificate must fail.+ std::fs::create_dir_all(data_dir.join("xerj.crt")).unwrap();++ let (rest, grpc, es) = three_free_ports();+ let config = format!(+ r#"+[server]+bind_address = "127.0.0.1"+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"++[tls]+enabled = true+cert_path = "{root}/missing.crt"+key_path = "{root}/missing.key"+"#,+ data = toml_path(&data_dir),+ root = toml_path(dir.path()),+ );+ let config_path = dir.path().join("xerj.toml");+ std::fs::write(&config_path, config).unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn xerj");++ // The fixed binary aborts at step 6 of startup, before metrics, engine+ // replay, or any listener — well under a second even on a 2-core CI+ // runner; 60 s is pure headroom. A regressed binary serves forever, so+ // bound the wait and treat "still running" as the downgrade it is.+ let deadline = Instant::now() + Duration::from_secs(60);+ let status = loop {+ match child.try_wait().expect("poll child") {+ Some(status) => break status,+ None if Instant::now() > deadline => {+ child.kill().ok();+ child.wait().ok();+ panic!(+ "xerj kept running although TLS could not be established — \+ it downgraded to plain HTTP instead of failing closed"+ );+ }+ None => std::thread::sleep(Duration::from_millis(100)),+ }+ };++ let mut stderr = String::new();+ child+ .stderr+ .take()+ .expect("stderr piped")+ .read_to_string(&mut stderr)+ .expect("read child stderr");++ assert!(+ !status.success(),+ "a TLS setup failure must exit non-zero, got {status:?}; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("TLS") && stderr.contains("refusing to start"),+ "the exit reason must name TLS and the refusal, so the operator \+ learns why the server would not come up; stderr:\n{stderr}"+ );+}