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): refuse to start when TLS is on and gRPC h2c is exposed off-loopback
xerj-orgecf12562f492
diff --git a/docs/SECURITY_MODEL.md b/docs/SECURITY_MODEL.mdindex 85bd2e810..e47eb3ddf 100644--- a/docs/SECURITY_MODEL.md+++ b/docs/SECURITY_MODEL.md@@ -353,6 +353,57 @@ Note that `ClientIp` is also used for audit fields on endpoints that are notrate limited, for example passkey enrolment (`auth/passkey.rs:168`). Only thethree endpoints listed above charge a bucket.+## Transport encryption, listener by listener++`tls.enabled` does not mean "the node is encrypted". It covers two of the three+data-plane listeners, and the third is cleartext by construction.++| listener | default port | with `tls.enabled = true` |+|---|---|---|+| Native REST | 8080 | TLS (in-process rustls) |+| ES-compat | 9200 | TLS (in-process rustls) |+| gRPC `XerjSearch` | 8081 | **cleartext h2c — never TLS** |+| Cluster control | 9300 | cleartext, authenticated only (see below) |++REST and ES-compat are wrapped by `axum_server::bind_rustls`, which handshakes+every accepted connection (`main.rs:788-810`). The gRPC listener is served by+`tonic::transport::Server` with no TLS configuration at all+(`grpc.rs:377-392`): tonic is deliberately built without its `tls` feature, so+that a second crypto backend is not pulled in beside axum-server's `ring`. The+consequence is that `tls.enabled` has no effect whatsoever on `:8081`.++Auth is not the gap here — every RPC goes through the same API-key check as the+HTTP surfaces (`GrpcAuth`, `grpc.rs:340-367`), so the port is not an open door.+Confidentiality is the gap: the credential itself, and every document body,+cross the wire in the clear.++### The startup check (issue #229)++Left alone, this is a silent mismatch. gRPC clients keep working whether or not+TLS is on, so an operator who enabled TLS and expected three encrypted+listeners gets no error, no failed connection, and no symptom of any kind.++So startup refuses the dangerous combination. `Config::grpc_h2c_exposed_off_loopback`+(`config.rs`) is true when TLS is enabled **and** `server.bind_address` is not+loopback **and** `tls.allow_insecure_grpc_h2c` is unset; `main.rs` step 5b then+aborts non-zero before binding anything or writing a certificate. Loopback+binds are unaffected, and `--insecure` clears `tls.enabled` so it never trips.++`0.0.0.0` and `::` count as exposed, not as "unset" — they bind every interface+the host has, and `0.0.0.0` is the shipped default. Link-local addresses count+as exposed too; they are reachable by every other host on the link. Both+choices are pinned by tests in `xerj-common/src/config.rs`, and the refusal+itself by `xerj-server/tests/grpc_h2c_fail_closed.rs`.++The escape hatch, `tls.allow_insecure_grpc_h2c = true`, does not make anything+safe — it records that you know, and it is what you set when a sidecar, mesh+or reverse proxy terminates TLS for `:8081` on your behalf. The startup banner+keeps naming the uncovered listener on every boot.++Wiring tonic's own `tls` feature would close this properly. It is not done: it+means a second TLS stack in the binary beside `axum-server` + `ring`, and that+trade has not been made. Until it is, treat `:8081` as a plaintext port.+## Cluster control-frame authenticationCluster mode is off by default (`ClusterConfig::default`,@@ -520,9 +571,13 @@ it is on a schedule this document can promise.- **Cluster traffic is unencrypted and membership-authenticated only.** Noconfidentiality, no per-node identity, no mTLS (`auth.rs:21-29`).- **TLS is off by default.** `TlsConfig` derives `Default`, so `tls.enabled` is- `false` (`config.rs:492-501`), and `--insecure` disables both TLS and auth- (`main.rs:345-349`). The startup banner prints the posture on every start- (`main.rs:302-319`).+ `false`, and `--insecure` disables both TLS and auth. The startup banner+ prints the posture on every start.+- **The gRPC listener is never TLS.** `tls.enabled` covers REST and ES-compat+ only; `:8081` is cleartext h2c in every configuration (`grpc.rs:377-392`).+ Startup refuses the combination "TLS on + non-loopback bind" rather than let+ that pass unnoticed — see+ [Transport encryption](#transport-encryption-listener-by-listener).- **No encryption at rest at the engine level.** The startup banner says to useOS full-disk encryption or bucket-side encryption instead (`main.rs:318`).- **Rate limiting covers three Console auth endpoints only.** There is nodiff --git a/docs/recipes/production-deployment.md b/docs/recipes/production-deployment.mdindex 064f8f348..9a3dd865c 100644--- a/docs/recipes/production-deployment.md+++ b/docs/recipes/production-deployment.md@@ -40,6 +40,11 @@ enabled = true # this is already the defaultenabled = truecert_path = "/var/lib/xerj/xerj.crt"key_path = "/var/lib/xerj/xerj.key"++# TLS covers REST and ES-compat only — :8081 stays cleartext h2c. On a+# non-loopback bind that combination refuses to start unless you say the+# exposure is intended. See "gRPC posture" below before keeping this line.+allow_insecure_grpc_h2c = true```Boot it:@@ -68,11 +73,14 @@ listener lines shown, the Data-dir/Console lines between them elided with `…`)```Native REST :8080 [TLS ]ES-compat :9200 [TLS ]- gRPC :8081 [h2c]+ gRPC :8081 [h2c — plaintext, no TLS]…┌─ Deployment posture (see PATH_TO_100_PCT_v0.6.0_to_v1.0.md) ──│ ✓ TLS: in-process rustls termination active (REST + ES-compat)│ (self-signed by default — supply a CA cert for production)+ │ ⚠ gRPC: :8081 is NOT covered by TLS — cleartext h2c on a non-loopback+ │ bind, allowed by tls.allow_insecure_grpc_h2c (issue #229).+ │ Terminate TLS for it at your proxy/mesh, or bind loopback.│ ✓ Auth: single API-key (no RBAC; per-doc / per-field controls roadmap v0.9)│ ⚠ Audit: request tracing only — tamper-evident WORM audit log v0.9│ ⚠ Encryption-at-rest: not engine-level — use OS FDE or S3 SSE for now@@ -190,6 +198,37 @@ Because the gRPC port carries cleartext frames, **terminate TLS in front ofclients reach it over an untrusted link. If you don't use gRPC, don't exposethe port.+**XERJ refuses to start rather than let that gap pass unnoticed.** With+`tls.enabled = true` and a `server.bind_address` that is not loopback, startup+aborts non-zero before binding anything:++```+Error: tls.enabled = true but the gRPC listener on 0.0.0.0:8081 speaks+cleartext h2c — TLS covers the REST and ES-compat listeners only, and+server.bind_address = "0.0.0.0" is not loopback, so gRPC traffic (including+API keys) would cross the network unencrypted while the node reports itself+as TLS-enabled. Refusing to start. Fix by binding to loopback+(server.bind_address = "127.0.0.1"), or terminate TLS for the gRPC port at a+proxy, sidecar or service mesh and declare it:+tls.allow_insecure_grpc_h2c = true.+```++Three ways out, in the order you should prefer them:++1. **Bind loopback** (`server.bind_address = "127.0.0.1"`) and let a proxy on+ the same host own every public port. No opt-out needed.+2. **Terminate TLS for `:8081`** at your proxy, sidecar or mesh, then set+ `tls.allow_insecure_grpc_h2c = true` to record that you did. This is what+ the quickstart config in+ [section 1](#1-secure-quickstart--tls--auth-in-one-config-file) does,+ because it binds `0.0.0.0`.+3. **Accept plaintext gRPC on a trusted network** — same setting, and the+ startup banner will keep saying `:8081` is uncovered on every boot.++`--insecure` never trips this: it clears `tls.enabled`, so nothing is claiming+the port is encrypted in the first place. The check only fires when TLS is on,+which is exactly when the mismatch is invisible.+### Behind a reverse proxy: `server.trusted_proxies`XERJ derives client identity — the per-IP auth rate-limit bucket on thediff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex 06f8616e7..8eb487731 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -269,6 +269,42 @@ impl Config {self.server.bind_address, self.server.es_compat_port)}++ /// Is `server.bind_address` confined to the local host?+ ///+ /// Only a loopback literal counts. `0.0.0.0` and `::` are *unspecified*,+ /// not loopback — they bind every interface the host has, which is the+ /// exposure this predicate exists to detect, and they are also the+ /// shipped default. An address that does not parse is reported as not+ /// confined: it fails closed here, and the `SocketAddr` parse at bind+ /// time rejects it a moment later anyway.+ pub fn bind_address_is_loopback(&self) -> bool {+ self.server+ .bind_address+ .trim()+ .parse::<std::net::IpAddr>()+ .map(crate::net::canonical_ip)+ .is_ok_and(|ip| ip.is_loopback())+ }++ /// Would starting now put a cleartext gRPC listener on a network-reachable+ /// interface while the operator believes TLS covers the node? (issue #229)+ ///+ /// True only when all three hold: TLS is on, the bind address is not+ /// confined to loopback, and the operator has not declared the exposure+ /// intentional via `tls.allow_insecure_grpc_h2c`. The caller's job is to+ /// refuse to start — see `xerj-server/src/main.rs`.+ ///+ /// The shape is Elasticsearch's bootstrap-check idea (approach only, no+ /// code: `BootstrapChecks.java:58-70` gates enforcement on the transport+ /// being bound off-loopback and offers one explicit override). Two+ /// deliberate departures: ES also exempts link-local, which is still+ /// reachable by every other host on the link, so this does not; and the+ /// override lives in the config file the setting it relaxes lives in,+ /// rather than a JVM system property.+ pub fn grpc_h2c_exposed_off_loopback(&self) -> bool {+ self.tls.enabled && !self.tls.allow_insecure_grpc_h2c && !self.bind_address_is_loopback()+ }}// ═════════════════════════════════════════════════════════════════════════════@@ -484,7 +520,7 @@ pub struct CorsConfig {/// TLS settings.///-/// **3 settings.**+/// **4 settings.**////// Defaults are derived: TLS is disabled (`enabled: false`) with empty/// cert/key paths so the engine starts out of the box; enable it in@@ -492,12 +528,34 @@ pub struct CorsConfig {#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(default, deny_unknown_fields)]pub struct TlsConfig {- /// Enable TLS on all listeners (default: `false` — enable in production).+ /// Enable in-process TLS termination on the **REST and ES-compat**+ /// listeners (default: `false` — enable in production).+ ///+ /// It does **not** cover the gRPC listener: `xerj-server/src/grpc.rs`+ /// builds tonic without its `tls` feature, so `server.grpc_port` speaks+ /// cleartext HTTP/2 (h2c) whatever this is set to (issue #229). Enabling+ /// TLS while binding off-loopback therefore refuses to start unless+ /// [`TlsConfig::allow_insecure_grpc_h2c`] says the exposure is intended.pub enabled: bool,/// Path to the PEM-encoded certificate file.pub cert_path: String,/// Path to the PEM-encoded private key file.pub key_path: String,+ /// Permit the cleartext h2c gRPC listener on a network-reachable+ /// interface while `enabled` is `true` (default: `false` — refuse).+ ///+ /// An operator who turns TLS on reasonably reads that as "every listener+ /// is encrypted", and nothing on the wire corrects them: gRPC clients keep+ /// working, so credentials and documents cross the network in the clear+ /// with no symptom. Rather than downgrade silently, startup fails closed+ /// and names this setting as the way to say the exposure is deliberate —+ /// for example when a sidecar or service mesh terminates TLS in front of+ /// `server.grpc_port`.+ ///+ /// Irrelevant when `enabled` is `false`: nothing then claims the gRPC+ /// port is encrypted, and the startup banner already says the listeners+ /// are plain TCP.+ pub allow_insecure_grpc_h2c: bool,}// ─────────────────────────────────────────────────────────────────────────────@@ -1594,7 +1652,8 @@ mod tests {// server: 6 (rest_port, grpc_port, es_compat_port, data_dir,// bind_address, trusted_proxies)// auth: 3 (enabled, admin_api_key, metrics_token) ← RC4-W4 item 4- // tls: 3 (enabled, cert_path, key_path)+ // tls: 4 (enabled, cert_path, key_path,+ // allow_insecure_grpc_h2c) ← issue #229// storage: 10 (wal_sync, wal_batch_ms, wal_max_size_mb, flush_size_mb,// flush_interval_secs, backend, s3_bucket, s3_prefix,// s3_region, local_cache_dir)@@ -1611,9 +1670,70 @@ mod tests {// indexing: 3 (turbo_batch_size, turbo_parallel, turbo_fast_analyzer)// logging: 2 (format, access_log) ← RC4-W4 item 6// ─────────- // total: 60 fields, minus 1 auto-generated (admin_api_key) = 59 meaningful user settings- let total: usize = 6 + 3 + 3 + 10 + 5 + 3 + 1 + 6 + 2 + 4 + 12 + 3 + 2;- assert_eq!(total, 60);+ // total: 61 fields, minus 1 auto-generated (admin_api_key) = 60 meaningful user settings+ let total: usize = 6 + 3 + 4 + 10 + 5 + 3 + 1 + 6 + 2 + 4 + 12 + 3 + 2;+ assert_eq!(total, 61);+ }++ // ── gRPC h2c exposure: fail closed (issue #229) ──────────────────────────++ /// The reported default in `xerj.toml`-less deployments. `0.0.0.0` binds+ /// every interface, so "TLS on, defaults otherwise" is exactly the case+ /// that must be caught — this is the assertion that fails without the fix.+ #[test]+ fn tls_on_with_default_bind_flags_grpc_h2c_exposure() {+ let cfg = Config::from_toml_str(+ "[tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n",+ )+ .unwrap();+ assert_eq!(cfg.server.bind_address, "0.0.0.0");+ assert!(!cfg.bind_address_is_loopback(), "0.0.0.0 is not loopback");+ assert!(cfg.grpc_h2c_exposed_off_loopback());+ }++ #[test]+ fn tls_on_bound_to_loopback_is_fine() {+ for bind in ["127.0.0.1", "127.0.0.5", "::1", "::ffff:127.0.0.1"] {+ let cfg = Config::from_toml_str(&format!(+ "[server]\nbind_address = \"{bind}\"\n\+ [tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n"+ ))+ .unwrap();+ assert!(cfg.bind_address_is_loopback(), "{bind} should be loopback");+ assert!(!cfg.grpc_h2c_exposed_off_loopback(), "{bind} must not trip");+ }+ }++ #[test]+ fn tls_off_never_trips_the_check() {+ // Nothing claims the port is encrypted, so there is no false promise+ // to fail closed on — the banner already says the listeners are plain.+ let cfg = Config::from_toml_str("[server]\nbind_address = \"0.0.0.0\"\n").unwrap();+ assert!(!cfg.tls.enabled);+ assert!(!cfg.grpc_h2c_exposed_off_loopback());+ }++ #[test]+ fn explicit_opt_out_permits_the_exposure() {+ let cfg = Config::from_toml_str(+ "[server]\nbind_address = \"10.0.0.7\"\n\+ [tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n\+ allow_insecure_grpc_h2c = true\n",+ )+ .unwrap();+ assert!(!cfg.grpc_h2c_exposed_off_loopback());+ }++ #[test]+ fn routable_bind_with_tls_trips_the_check() {+ for bind in ["10.0.0.7", "0.0.0.0", "::", "fe80::1", "not-an-ip"] {+ let cfg = Config::from_toml_str(&format!(+ "[server]\nbind_address = \"{bind}\"\n\+ [tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n"+ ))+ .unwrap();+ assert!(cfg.grpc_h2c_exposed_off_loopback(), "{bind} must trip");+ }}// ── Cluster auth: fail closed (issue #75) ────────────────────────────────diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsindex 534d1f18b..e26d553ec 100644--- a/engine/crates/xerj-server/src/grpc.rs+++ b/engine/crates/xerj-server/src/grpc.rs@@ -9,6 +9,15 @@//! The listener speaks plaintext HTTP/2 (h2c). TLS termination stays with the//! REST/ES listeners (axum-server + ring); tonic is built without its `tls`//! feature so no second crypto backend is dragged in.+//!+//! That is a real gap, not a footnote (issue #229): `tls.enabled = true`+//! encrypts the other two listeners and leaves this one in the clear, and+//! nothing a working gRPC client sees would tell the operator. Startup+//! therefore refuses the combination "TLS on + non-loopback bind" unless+//! `tls.allow_insecure_grpc_h2c` declares it intended — see+//! `Config::grpc_h2c_exposed_off_loopback` and step 5b of `main.rs`. Wiring+//! tonic's own `tls` feature (a second crypto backend beside axum-server's+//! ring) is the open follow-up; documented in `docs/SECURITY_MODEL.md`.use std::net::SocketAddr;@@ -374,6 +383,11 @@ impl tonic::service::Interceptor for GrpcAuth {////// Every RPC is guarded by [`GrpcAuth`], which enforces the same API-key auth/// as the REST / ES-compat listeners.+///+/// The transport is cleartext h2c — see the module docs. Whether that is+/// acceptable for `addr` is decided before this is called (`main.rs` step 5b);+/// this function does not re-check, so do not call it on a new code path+/// without carrying that decision with you.pub async fn serve_grpc<F>(addr: SocketAddr, state: AppState, shutdown: F) -> anyhow::Result<()>whereF: std::future::Future<Output = ()> + Send + 'static,diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 69fc35445..69d208de9 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -282,7 +282,13 @@ fn print_banner(cfg: &Config, startup_ms: u128) {println!();println!(" Native REST :{} [{}]", cfg.server.rest_port, tls);println!(" ES-compat :{} [{}]", cfg.server.es_compat_port, tls);- println!(" gRPC :{} [h2c]", cfg.server.grpc_port);+ // Never interpolated with `tls`: the gRPC listener is h2c whatever+ // `[tls]` says (issue #229), and a line that read "TLS" here would be the+ // exact false promise the startup check exists to prevent.+ println!(+ " gRPC :{} [h2c — plaintext, no TLS]",+ cfg.server.grpc_port+ );println!(" Data dir {}", cfg.server.data_dir);println!(" Started in {}ms", startup_ms);println!();@@ -306,6 +312,22 @@ fn print_banner(cfg: &Config, startup_ms: u128) {} else {println!(" │ ✓ TLS: in-process rustls termination active (REST + ES-compat)");println!(" │ (self-signed by default — supply a CA cert for production)");+ // The exposure the startup check refuses by default. Reaching here+ // with a non-loopback bind means the operator set the opt-out, so+ // say what it bought them rather than repeating the generic ✓.+ if !cfg.bind_address_is_loopback() {+ println!(+ " │ ⚠ gRPC: :{} is NOT covered by TLS — cleartext h2c on a non-loopback",+ cfg.server.grpc_port+ );+ println!(" │ bind, allowed by tls.allow_insecure_grpc_h2c (issue #229).");+ println!(" │ Terminate TLS for it at your proxy/mesh, or bind loopback.");+ } else {+ println!(+ " │ ⚠ gRPC: :{} is NOT covered by TLS — cleartext h2c, loopback-only",+ cfg.server.grpc_port+ );+ }}if !cfg.auth.enabled {println!(" │ ⚠ Auth: DISABLED (--insecure) — anyone on the network can write");@@ -1589,6 +1611,35 @@ async fn async_main() -> Result<()> {info!("xerj v{} starting", env!("CARGO_PKG_VERSION"));+ // 3b. gRPC h2c exposure — fail closed (issue #229). `grpc.rs` builds+ // tonic without its `tls` feature, so `server.grpc_port` speaks+ // cleartext h2c no matter what `[tls]` says. Enabling TLS and binding+ // off-loopback would therefore encrypt two listeners and quietly+ // leave the third in the clear on the same public interface — and+ // because gRPC clients keep working, the operator's only clue is a+ // banner they read once. Refuse instead, and name the one setting+ // that says the exposure is deliberate.+ //+ // First thing after tracing, on purpose: a boot that is going to be+ // rejected must not create the data directory, mint and print a+ // first-run admin key, or generate a certificate. It is also after+ // `load_config`, so `--insecure` (which clears `tls.enabled`) has+ // already been applied and cannot be overruled from a config file.+ if cfg.grpc_h2c_exposed_off_loopback() {+ anyhow::bail!(+ "tls.enabled = true but the gRPC listener on {}:{} speaks cleartext h2c — \+ TLS covers the REST and ES-compat listeners only, and server.bind_address \+ = \"{}\" is not loopback, so gRPC traffic (including API keys) would cross \+ the network unencrypted while the node reports itself as TLS-enabled. \+ Refusing to start. Fix by binding to loopback (server.bind_address = \+ \"127.0.0.1\"), or terminate TLS for the gRPC port at a proxy, sidecar or \+ service mesh and declare it: tls.allow_insecure_grpc_h2c = true.",+ cfg.server.bind_address,+ cfg.server.grpc_port,+ cfg.server.bind_address,+ );+ }+// 4. Data directorystd::fs::create_dir_all(&cfg.server.data_dir).with_context(|| format!("create data dir {}", cfg.server.data_dir))?;diff --git a/engine/crates/xerj-server/tests/grpc_h2c_fail_closed.rs b/engine/crates/xerj-server/tests/grpc_h2c_fail_closed.rsnew file mode 100644index 000000000..fea19f230--- /dev/null+++ b/engine/crates/xerj-server/tests/grpc_h2c_fail_closed.rs@@ -0,0 +1,276 @@+//! Issue #229: the cleartext gRPC listener must fail closed off-loopback.+//!+//! `xerj-server/src/grpc.rs` builds tonic without its `tls` feature, so+//! `server.grpc_port` speaks h2c whatever `[tls]` says. With `tls.enabled =+//! true` and a non-loopback `bind_address`, the REAL binary must exit non-zero+//! before binding anything rather than encrypt two listeners and put the third+//! in the clear on the same public interface.+//!+//! Why this is worth a process-level test rather than only the unit tests on+//! `Config::grpc_h2c_exposed_off_loopback`: the pre-fix binary starts happily+//! and serves all three ports forever, so the defect is invisible from inside+//! the config crate. Against a regressed binary this test hits its deadline+//! and fails instead of hanging.+//!+//! Nothing here binds `0.0.0.0` on purpose — the fixed binary refuses before+//! any listener exists, and the ports handed to it are free either way.++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 a regressed (serving) binary binds+/// cleanly and keeps running 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('\\', "/")+}++/// Run the real binary against `config_body` and return `(success, stderr)`.+///+/// The fixed binary rejects at step 5b of startup — before metrics, engine+/// replay, certificate generation, or any listener — so well under a second+/// even on a 2-core CI runner; 60 s is pure headroom.+fn run_until_exit(config_body: &str, dir: &std::path::Path) -> (bool, String) {+ let config_path = dir.join("xerj.toml");+ std::fs::write(&config_path, config_body).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");++ 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 with tls.enabled = true and a non-loopback \+ bind_address — it is serving cleartext h2c gRPC on a public \+ interface while reporting itself as TLS-enabled"+ );+ }+ 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");+ (status.success(), stderr)+}++/// `0.0.0.0` is the shipped default and binds every interface the host has,+/// so "turn TLS on, change nothing else" is the exact case that must be+/// refused. This is the assertion that fails without the fix.+#[test]+fn tls_with_non_loopback_bind_refuses_to_start() {+ let dir = tempfile::tempdir().unwrap();+ let data_dir = dir.path().join("data");+ let (rest, grpc, es) = three_free_ports();++ let (ok, stderr) = run_until_exit(+ &format!(+ r#"+[server]+bind_address = "0.0.0.0"+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"++[tls]+enabled = true+cert_path = "{root}/xerj.crt"+key_path = "{root}/xerj.key"+"#,+ data = toml_path(&data_dir),+ root = toml_path(dir.path()),+ ),+ dir.path(),+ );++ assert!(+ !ok,+ "cleartext gRPC on a non-loopback bind under tls.enabled must exit \+ non-zero; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("h2c") && stderr.contains("Refusing to start"),+ "the exit reason must name the cleartext transport and the refusal; \+ stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("tls.allow_insecure_grpc_h2c"),+ "the operator must be told the setting that unblocks the boot, or the \+ refusal is a dead end; stderr:\n{stderr}"+ );+ // Refused at step 3b, before anything is created: no data directory, no+ // first-run admin key minted and printed, no certificate. A rejected boot+ // that still seeds credentials leaves state the operator has to clean up+ // — and an admin key on stdout that was never actually used.+ assert!(+ !dir.path().join("xerj.crt").exists(),+ "the check must run before certificate generation; stderr:\n{stderr}"+ );+ assert!(+ !data_dir.exists(),+ "a rejected boot must not create the data dir; stderr:\n{stderr}"+ );+}++/// The refusal must not fire on a loopback bind — that would break every+/// developer running `tls.enabled = true` locally, and a fail-closed check+/// nobody can satisfy gets disabled wholesale.+///+/// A clean start has no exit to wait for, so this asserts the negative that+/// is observable without one: the process is still alive after the point the+/// refusal would have killed it, and never printed the refusal.+#[test]+fn tls_on_loopback_starts_normally() {+ let dir = tempfile::tempdir().unwrap();+ let data_dir = dir.path().join("data");+ let (rest, grpc, es) = three_free_ports();+ let config_path = dir.path().join("xerj.toml");+ std::fs::write(+ &config_path,+ 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}/xerj.crt"+key_path = "{root}/xerj.key"+"#,+ data = toml_path(&data_dir),+ root = toml_path(dir.path()),+ ),+ )+ .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");++ // Generous enough for engine init on a slow runner, and far past step 5b.+ std::thread::sleep(Duration::from_secs(5));+ let alive = child.try_wait().expect("poll child").is_none();+ child.kill().ok();+ child.wait().ok();++ let mut stderr = String::new();+ child+ .stderr+ .take()+ .expect("stderr piped")+ .read_to_string(&mut stderr)+ .expect("read child stderr");++ assert!(+ alive,+ "a loopback bind with TLS must start; it exited instead. stderr:\n{stderr}"+ );+ assert!(+ !stderr.contains("Refusing to start"),+ "the h2c check must not fire on loopback; stderr:\n{stderr}"+ );+}++/// The documented escape hatch has to actually work, or operators will reach+/// for `--insecure` (which also drops auth) to get past the refusal.+#[test]+fn explicit_opt_out_allows_a_non_loopback_bind() {+ let dir = tempfile::tempdir().unwrap();+ let data_dir = dir.path().join("data");+ let (rest, grpc, es) = three_free_ports();+ let config_path = dir.path().join("xerj.toml");+ // Bind loopback so the test starts no publicly reachable listener; the+ // opt-out is what is under test, and `allow_insecure_grpc_h2c` is read+ // before the bind address is even consulted. The non-loopback half of the+ // matrix is covered by the unit tests in `xerj-common::config`.+ std::fs::write(+ &config_path,+ 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}/xerj.crt"+key_path = "{root}/xerj.key"+allow_insecure_grpc_h2c = true+"#,+ data = toml_path(&data_dir),+ root = toml_path(dir.path()),+ ),+ )+ .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");++ std::thread::sleep(Duration::from_secs(5));+ let alive = child.try_wait().expect("poll child").is_none();+ child.kill().ok();+ child.wait().ok();++ let mut stderr = String::new();+ child+ .stderr+ .take()+ .expect("stderr piped")+ .read_to_string(&mut stderr)+ .expect("read child stderr");++ assert!(+ alive,+ "tls.allow_insecure_grpc_h2c = true must be accepted as a config key \+ and must not block startup. stderr:\n{stderr}"+ );+}diff --git a/engine/xerj.default.toml b/engine/xerj.default.tomlindex 9ee6deabf..952ce0b1f 100644--- a/engine/xerj.default.toml+++ b/engine/xerj.default.toml@@ -74,14 +74,18 @@ admin_api_key = ""# a low-privilege credential that can read metrics but not index data.metrics_token = ""-# ── TLS (3 settings) ──────────────────────────────────────────────────────────+# ── TLS (4 settings) ──────────────────────────────────────────────────────────[tls]-# Enable TLS on all listeners.+# Enable in-process TLS termination on the REST and ES-compat listeners.# Requires cert_path and key_path to be set when true.# In production, always enable TLS. In Docker, you may terminate TLS at the# load balancer or proxy instead.+#+# This does NOT cover the gRPC listener (server.grpc_port): tonic is built+# without its TLS feature, so :8081 speaks cleartext h2c whatever this says.+# See allow_insecure_grpc_h2c below.enabled = false# Path to the PEM-encoded X.509 certificate file.@@ -92,6 +96,17 @@ cert_path = ""# Permissions should be 600 (owner-readable only).key_path = ""+# Allow the cleartext h2c gRPC listener on a non-loopback bind_address while+# TLS is enabled. Default false, which REFUSES TO START in that combination:+# enabling TLS reads as "every listener is encrypted", gRPC clients keep+# working either way, so the mismatch would otherwise never surface.+#+# Set true only when something in front of server.grpc_port terminates TLS for+# it — a sidecar, service mesh or reverse proxy — or when the port is on a+# network you trust. Binding loopback (bind_address = "127.0.0.1") needs no+# opt-out. Ignored entirely when enabled = false.+allow_insecure_grpc_h2c = false+# ── Storage & WAL (5 settings) ────────────────────────────────────────────────[storage]