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): bind loopback by default, refuse a cleartext network bind (#228)
xerj-org1f789b212ab0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 00ff4fc62..85463e0b8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- **BREAKING — `server.bind_address` now defaults to `127.0.0.1`, and a+ cleartext node refuses to publish itself to the network**+ ([#228](https://github.com/xerj-org/xerj/issues/228)). The old default was+ `0.0.0.0` while TLS is off by default, so an out-of-the-box node accepted its+ admin API key over plain HTTP on every interface the host had — verified on a+ stock boot, where `curl -H "Authorization: ApiKey …" http://<lan-ip>:9200/…`+ answered `200` and the same URL over `https` had no listener to hand shake+ with. Auth being on did not help: the credential *is* the thing on the wire.++ A fresh node is now reachable from its own host and nowhere else. Exposing it+ is two statements, not zero: set `server.bind_address` (or `--bind` /+ `XERJ_BIND_ADDRESS`), and — while `tls.enabled = false` — also set+ `server.allow_insecure_network_bind = true` (env+ `XERJ_ALLOW_INSECURE_NETWORK_BIND`). Without the second, startup exits+ non-zero before the data directory is created or a first-run admin key is+ minted. `--insecure` does not evade it; it clears `tls.enabled`, which is+ exactly what the check keys on. Same fail-closed shape as+ [#229](https://github.com/xerj-org/xerj/issues/229), whose TLS-on gRPC check+ is untouched and cannot be relaxed by this opt-out.++ **Upgrading:** a deployment that relied on the old default becomes+ unreachable from other hosts until it sets both; one that already wrote+ `bind_address = "0.0.0.0"` without TLS now fails to start with a message+ naming the setting that unblocks it. The shipped Docker image, compose file+ and Helm chart set both, because a container's network namespace is the+ boundary and its published port is where TLS belongs.++ Two documentation claims that were false as written are now true: the CLI and+ security pages both said `--insecure` "refuses to run with a non-loopback+ bind", and it did not — a `--insecure` node on `0.0.0.0` accepted an+ unauthenticated `PUT /leak/_doc/1` from the LAN (`201`). The startup banner+ also prints the bind address on every listener line, so a loopback node and a+ world-facing one no longer look identical.+### Fixed- **`autoindex` no longer leaves immortal catalog entries for skipped files**diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ac19292de..ecdd1526e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -26,7 +26,9 @@ cargo build --release -p xerj-server # the server binarycargo build --release # everything```-Run the server locally (insecure = no TLS, no auth; listens on `http://0.0.0.0:9200`):+Run the server locally (insecure = no TLS, no auth; listens on+`http://127.0.0.1:9200` — the default bind is loopback, and `--insecure` on a+non-loopback bind refuses to start):```bash./target/release/xerj --data-dir ./data --insecurediff --git a/deploy/helm/xerj/templates/statefulset.yaml b/deploy/helm/xerj/templates/statefulset.yamlindex e719c4d2f..4fd109ccb 100644--- a/deploy/helm/xerj/templates/statefulset.yaml+++ b/deploy/helm/xerj/templates/statefulset.yaml@@ -64,6 +64,12 @@ spec:env:- name: XERJ_LOGvalue: "info"+ # Engine issue #228: the default bind is loopback, which a pod+ # cannot use — probes and the Service arrive on the pod IP.+ - name: XERJ_BIND_ADDRESS+ value: {{ .Values.network.bindAddress | quote }}+ - name: XERJ_ALLOW_INSECURE_NETWORK_BIND+ value: {{ .Values.network.allowInsecureNetworkBind | quote }}volumeMounts:- name: datamountPath: /datadiff --git a/deploy/helm/xerj/values.yaml b/deploy/helm/xerj/values.yamlindex c9211fb0b..ca34e0788 100644--- a/deploy/helm/xerj/values.yaml+++ b/deploy/helm/xerj/values.yaml@@ -61,6 +61,22 @@ probes:# default is the configuration most users will ever run.insecure: false+# Network exposure (engine issue #228).+#+# xerj binds 127.0.0.1 by default so a bare install cannot publish an API key+# in cleartext to every interface. A pod must bind 0.0.0.0 or nothing works:+# kubelet's liveness/readiness probes and the Service both reach it on the pod+# IP, not on loopback. The pod network is the boundary, and the chart says so+# explicitly rather than letting the engine default it away.+#+# What that means for you: traffic between a client and this pod is plain HTTP+# unless you terminate TLS in front of it (Ingress, gateway, or a service mesh+# with mTLS). Set tls.enabled below to terminate it in-process instead — then+# allowInsecureNetworkBind is ignored.+network:+ bindAddress: "0.0.0.0"+ allowInsecureNetworkBind: true+tls:enabled: falsecertPath: /etc/xerj/tls.crtdiff --git a/docs/SECURITY_MODEL.md b/docs/SECURITY_MODEL.mdindex e47eb3ddf..bde1c6f78 100644--- a/docs/SECURITY_MODEL.md+++ b/docs/SECURITY_MODEL.md@@ -353,6 +353,68 @@ 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.+## Reach: what a fresh node exposes (issue #228)++`server.bind_address` defaults to **`127.0.0.1`**. A node you start without+configuring anything is reachable from the machine it runs on and from nowhere+else.++That default is chosen against the one that used to ship, `0.0.0.0`. Auth is on+by default and the admin key is generated 0600 on first start, which is the+part that is genuinely good — but TLS is *off* by default, so binding every+interface meant the admin API key travelled in an `Authorization` header over+plain HTTP to anything that could route to the host. Nothing about the+experience said so: `curl` worked, the health endpoint answered, and the key+was accepted. `user-feedback/09-security/insecure-defaults.md` collects the+field reports this is aimed at — a list of eight-and-nine-figure record+exposures whose common factor is a search node reachable from the internet in+whatever state it shipped in. A shipped default is the configuration most+installs will ever run.++### Exposing the node is a two-part statement++Set `server.bind_address` (or `--bind` / `XERJ_BIND_ADDRESS`) to `0.0.0.0` or a+specific address. With `tls.enabled = false`, startup then **refuses** unless+`server.allow_insecure_network_bind = true` (env:+`XERJ_ALLOW_INSECURE_NETWORK_BIND`).++`Config::cleartext_exposed_off_loopback` (`config.rs`) is true when TLS is off+**and** the bind address is not loopback **and** the opt-out is unset; `main.rs`+step 3c aborts non-zero before the data directory is created, before a first-run+admin key is minted and printed, and before any listener exists.++```+Error: server.bind_address = "0.0.0.0" is not loopback and tls.enabled = false,+so every listener (8080, 9200, 8081) would serve plain HTTP on a+network-reachable interface — the API key in every Authorization header, and+every document body, would cross the network in cleartext. Refusing to start.+…declare it: server.allow_insecure_network_bind = true (env:+XERJ_ALLOW_INSECURE_NETWORK_BIND=true).+```++Scope of the refusal, all pinned by tests:++- **`0.0.0.0` and `::` count as exposed**, not as "unset" — they bind every+ interface the host has.+- **Link-local counts as exposed too** — still reachable by every other host on+ the link.+- **Loopback binds are untouched**, so local development, the quickstarts and+ the ES-YAML conformance harness keep working with TLS off.+- **`--insecure` does not evade it.** It clears `tls.enabled`, so it trips the+ check like any other cleartext configuration — and it drops auth as well, so+ the configuration it would otherwise produce is an unauthenticated node on+ every interface.+- **The opt-out relaxes only this check.** With TLS on it is not consulted at+ all; the residual gRPC h2c exposure stays governed by+ `tls.allow_insecure_grpc_h2c` (#229).++The escape hatch does not make anything safe. It records that you know, and it+is what you set when a reverse proxy, sidecar, mesh or ingress terminates TLS in+front of the node — or when the boundary is a container's network namespace,+which is why the shipped Docker image and Helm chart set it. The startup banner+then names the exposure on every boot, and every listener line carries the bind+address so a loopback node and a world-facing one no longer look identical.+## Transport encryption, listener by listener`tls.enabled` does not mean "the node is encrypted". It covers two of the three@@ -390,8 +452,10 @@ aborts non-zero before binding anything or writing a certificate. Loopbackbinds 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+the host has. (They were also the shipped default until #228 made it loopback;+either way this check fires on what the config says, not on what it omits.)+Link-local addresses count as exposed too; they are reachable by every other+host on the link. Bothchoices are pinned by tests in `xerj-common/src/config.rs`, and the refusalitself by `xerj-server/tests/grpc_h2c_fail_closed.rs`.@@ -572,7 +636,13 @@ it is on a schedule this document can promise.confidentiality, no per-node identity, no mTLS (`auth.rs:21-29`).- **TLS is off by default.** `TlsConfig` derives `Default`, so `tls.enabled` is`false`, and `--insecure` disables both TLS and auth. The startup banner- prints the posture on every start.+ prints the posture on every start. The mitigation is reach, not encryption:+ the default bind is loopback and exposing the node in cleartext has to be+ declared — see [Reach](#reach-what-a-fresh-node-exposes-issue-228).+- **A declared cleartext exposure is still cleartext.** Nothing about+ `server.allow_insecure_network_bind = true` encrypts anything; it only means+ the operator said so. Every deployment that publishes a port — including the+ shipped Docker image and Helm chart — needs TLS terminated in front of it.- **The gRPC listener is never TLS.** `tls.enabled` covers REST and ES-compatonly; `:8081` is cleartext h2c in every configuration (`grpc.rs:377-392`).Startup refuses the combination "TLS on + non-loopback bind" rather than letdiff --git a/docs/recipes/production-deployment.md b/docs/recipes/production-deployment.mdindex 9a3dd865c..fec0652f9 100644--- a/docs/recipes/production-deployment.md+++ b/docs/recipes/production-deployment.md@@ -30,6 +30,12 @@ Create `xerj.toml`:[server]es_compat_port = 9200 # Elasticsearch-wire clients point heredata_dir = "/var/lib/xerj"++# The default is "127.0.0.1" — loopback only, so a node you have not thought+# about cannot be reached from the network. Exposing it is deliberate. With+# tls.enabled = false a non-loopback bind refuses to start unless you also set+# server.allow_insecure_network_bind = true; the TLS block below is what makes+# it unnecessary here.bind_address = "0.0.0.0"[auth]@@ -225,9 +231,54 @@ Three ways out, in the order you should prefer them:3. **Accept plaintext gRPC on a trusted network** — same setting, and thestartup 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.+`--insecure` never trips *this* check: it clears `tls.enabled`, so nothing is+claiming the port is encrypted in the first place. This one only fires when TLS+is on, which is exactly when the mismatch is invisible.++It trips the other one instead. See+[cleartext exposure](#cleartext-exposure-issue-228) below: with TLS off, a+non-loopback bind refuses to start for a broader reason — not one uncovered+listener but all of them.++### Cleartext exposure (issue #228)++`server.bind_address` defaults to `127.0.0.1`. A node started without a config+file is reachable only from its own host, because TLS is off by default and a+world-facing cleartext node would publish its admin API key to every interface.++Exposing the node is therefore two statements, not one:++```toml+[server]+bind_address = "0.0.0.0"+# Required whenever bind_address is not loopback AND tls.enabled = false.+# Unnecessary in the section-1 config above, which enables TLS.+allow_insecure_network_bind = true+```++Without the second line, startup aborts non-zero before creating the data+directory or minting a first-run admin key:++```+Error: server.bind_address = "0.0.0.0" is not loopback and tls.enabled = false,+so every listener (8080, 9200, 8081) would serve plain HTTP on a+network-reachable interface — the API key in every Authorization header, and+every document body, would cross the network in cleartext. Refusing to start.+```++Three ways out, in the order you should prefer them:++1. **Enable TLS** (section 1). Then this check is not consulted at all.+2. **Bind loopback** and let a proxy on the same host own the public ports.+3. **Declare the exposure** with `allow_insecure_network_bind = true` when+ something in front of the node already terminates TLS — ingress, sidecar,+ mesh — or when the boundary is a container network namespace. The startup+ banner keeps naming it on every boot.++Two conveniences exist because the default is loopback: `--bind 0.0.0.0` /+`XERJ_BIND_ADDRESS`, and `XERJ_ALLOW_INSECURE_NETWORK_BIND`, so a container can+express both without shipping a TOML file. The Docker image and the Helm chart+set exactly these.### Behind a reverse proxy: `server.trusted_proxies`diff --git a/engine/Dockerfile b/engine/Dockerfileindex 6ac6c8010..6e2e1c537 100644--- a/engine/Dockerfile+++ b/engine/Dockerfile@@ -18,6 +18,18 @@ RUN mkdir -p /dataEXPOSE 8080 9200 8081ENV XERJ_LOG=info+# xerj binds loopback by default (issue #228) so that a bare `xerj` cannot+# publish an API key in cleartext to every interface. A container has to bind+# 0.0.0.0 — the container's network namespace is itself the boundary, and+# nothing reaches the listeners until you publish a port or route a Service to+# it. That published port is where TLS belongs: terminate it at your ingress,+# proxy or mesh. The declaration is explicit here rather than defaulted into+# the engine, and the startup banner names the exposure on every boot.+#+# Override either variable to change it (`docker run -e XERJ_BIND_ADDRESS=...`).+ENV XERJ_BIND_ADDRESS=0.0.0.0+ENV XERJ_ALLOW_INSECURE_NETWORK_BIND=true+# Container HEALTHCHECK uses the v0.8 readiness probe — kubelet hits the# same endpoint via Helm-chart probe configs.HEALTHCHECK --interval=10s --timeout=2s --start-period=10s --retries=3 \diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex 8eb487731..4f08bb444 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -270,21 +270,45 @@ impl Config {)}+ /// `server.bind_address` as an [`IpAddr`](std::net::IpAddr), or `None` if+ /// it is not an IP literal.+ ///+ /// The single place the setting is interpreted, so every caller agrees on+ /// what it means. Surrounding brackets are accepted and stripped: a v6+ /// address is conventionally written `[::1]` next to a port, and an+ /// operator who copies that form into the config should not get a+ /// different answer than one who writes `::1`.+ ///+ /// Listeners must be composed with [`std::net::SocketAddr::new`] from this+ /// rather than by formatting `"{bind}:{port}"` — `"::1:9200"` is not a+ /// parseable socket address, which is how a `bind_address = "::1"` node+ /// used to fail at bind time with `invalid socket address syntax` after+ /// it had already created its data directory and printed a first-run link.+ pub fn bind_ip(&self) -> Option<std::net::IpAddr> {+ let raw = self.server.bind_address.trim();+ let raw = raw+ .strip_prefix('[')+ .and_then(|r| r.strip_suffix(']'))+ .unwrap_or(raw);+ raw.parse::<std::net::IpAddr>().ok()+ }++ /// `server.bind_address` and `port` as a bindable socket address.+ pub fn socket_addr(&self, port: u16) -> Option<std::net::SocketAddr> {+ self.bind_ip().map(|ip| std::net::SocketAddr::new(ip, 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.+ /// exposure this predicate exists to detect. An address that does not+ /// parse is reported as not confined: it fails closed here, and the bind+ /// itself rejects it a moment later anyway.pub fn bind_address_is_loopback(&self) -> bool {- self.server- .bind_address- .trim()- .parse::<std::net::IpAddr>()+ self.bind_ip().map(crate::net::canonical_ip)- .is_ok_and(|ip| ip.is_loopback())+ .is_some_and(|ip| ip.is_loopback())}/// Would starting now put a cleartext gRPC listener on a network-reachable@@ -305,6 +329,36 @@ impl Config {pub fn grpc_h2c_exposed_off_loopback(&self) -> bool {self.tls.enabled && !self.tls.allow_insecure_grpc_h2c && !self.bind_address_is_loopback()}++ /// Would starting now publish *every* listener in cleartext on a+ /// network-reachable interface? (issue #228)+ ///+ /// True when all three hold: TLS is off, the bind address is not confined+ /// to loopback, and the operator has not declared the exposure intentional+ /// via `server.allow_insecure_network_bind`. The caller's job is to refuse+ /// to start — see `xerj-server/src/main.rs`.+ ///+ /// This is the TLS-off half of the pair whose TLS-on half is+ /// [`Config::grpc_h2c_exposed_off_loopback`] (#229), and the two are+ /// mutually exclusive by construction: exactly one of them can fire for a+ /// given `tls.enabled`. The exposure here is strictly larger — with TLS+ /// off it is not one uncovered listener but all of them, carrying the+ /// `Authorization: ApiKey` header of every request.+ ///+ /// Same shape as ES's bootstrap checks (approach only, no code — AGPL):+ /// `BootstrapChecks.java:50-53` enforces "once a node has the transport+ /// protocol bound to a non-loopback interface … we assume the node is+ /// running in production", with one explicit override+ /// (`es.enforce.bootstrap.checks`, `:59`). Departures: the override lives+ /// in the config file beside the setting it relaxes rather than in a+ /// system property, and link-local counts as exposed here (ES's+ /// `enforceLimits`, `:194-197`, tests only `isLoopbackAddress`, but a+ /// link-local address is still reachable by every other host on the link).+ pub fn cleartext_exposed_off_loopback(&self) -> bool {+ !self.tls.enabled+ && !self.server.allow_insecure_network_bind+ && !self.bind_address_is_loopback()+ }}// ═════════════════════════════════════════════════════════════════════════════@@ -313,7 +367,7 @@ impl Config {/// Network and data-directory settings.///-/// **6 settings.**+/// **7 settings.**#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default, deny_unknown_fields)]pub struct ServerConfig {@@ -325,8 +379,38 @@ pub struct ServerConfig {pub es_compat_port: u16,/// Directory where index data is persisted (default: `"./data"`).pub data_dir: String,- /// Address to bind all listeners (default: `"0.0.0.0"`).+ /// Address to bind all listeners (default: `"127.0.0.1"` — **loopback+ /// only**; issue #228).+ ///+ /// A fresh node is reachable from the machine it runs on and nowhere+ /// else. That is deliberate: TLS is off by default, so an out-of-the-box+ /// node that bound every interface would put its admin API key and every+ /// document body on the network in cleartext, and nothing about a working+ /// `curl` would say so.+ ///+ /// Set this to expose the node — `"0.0.0.0"` for every interface, or a+ /// specific private address. Doing so while `tls.enabled = false` refuses+ /// to start unless [`ServerConfig::allow_insecure_network_bind`] says the+ /// cleartext exposure is intended; see+ /// [`Config::cleartext_exposed_off_loopback`].pub bind_address: String,+ /// Permit a network-reachable `bind_address` while TLS is off+ /// (default: `false` — refuse; issue #228).+ ///+ /// Binding off-loopback with `tls.enabled = false` means every request —+ /// including the `Authorization: ApiKey` header — crosses the network in+ /// the clear. That is a legitimate configuration when something in front+ /// of the node terminates TLS (reverse proxy, sidecar, service mesh,+ /// ingress controller) or when the link itself is trusted, and it is what+ /// a container image has to do because the container's network namespace+ /// is the boundary. It is *not* something to arrive at by accident, so it+ /// has to be stated rather than defaulted into.+ ///+ /// Irrelevant when `bind_address` is loopback (nothing off-host can reach+ /// the listeners) or when `tls.enabled = true` (REST and ES-compat are+ /// encrypted; the separate gRPC h2c exposure is governed by+ /// [`TlsConfig::allow_insecure_grpc_h2c`], issue #229).+ pub allow_insecure_network_bind: bool,/// Reverse proxies whose `X-Forwarded-For` / `X-Real-IP` headers may be/// believed (default: `[]` — **believe nobody**).///@@ -354,7 +438,11 @@ impl Default for ServerConfig {grpc_port: 8081,es_compat_port: 9200,data_dir: "./data".into(),- bind_address: "0.0.0.0".into(),+ // Loopback, not `0.0.0.0` (issue #228). TLS is off by default, so+ // the shipped default must not be one that publishes an API key+ // in cleartext to every interface the host happens to have.+ bind_address: "127.0.0.1".into(),+ allow_insecure_network_bind: false,trusted_proxies: Vec::new(),}}@@ -1649,8 +1737,9 @@ mod tests {#[test]fn count_user_facing_settings() {// 50 user-facing settings:- // server: 6 (rest_port, grpc_port, es_compat_port, data_dir,- // bind_address, trusted_proxies)+ // server: 7 (rest_port, grpc_port, es_compat_port, data_dir,+ // bind_address, allow_insecure_network_bind, ← #228+ // trusted_proxies)// auth: 3 (enabled, admin_api_key, metrics_token) ← RC4-W4 item 4// tls: 4 (enabled, cert_path, key_path,// allow_insecure_grpc_h2c) ← issue #229@@ -1670,23 +1759,28 @@ mod tests {// indexing: 3 (turbo_batch_size, turbo_parallel, turbo_fast_analyzer)// logging: 2 (format, access_log) ← RC4-W4 item 6// ─────────- // 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);+ // total: 62 fields, minus 1 auto-generated (admin_api_key) = 61 meaningful user settings+ let total: usize = 7 + 3 + 4 + 10 + 5 + 3 + 1 + 6 + 2 + 4 + 12 + 3 + 2;+ assert_eq!(total, 62);}// ── 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.+ /// `0.0.0.0` binds every interface, so "TLS on, bound to the world" is+ /// exactly the case that must be caught — this is the assertion that+ /// fails without the #229 fix.+ ///+ /// It used to reach `0.0.0.0` by saying nothing, because that was the+ /// shipped default; #228 made the default loopback, so the exposure is+ /// now written out. That is the point of the change, not an accident of+ /// it: this configuration has to be typed to happen.#[test]- fn tls_on_with_default_bind_flags_grpc_h2c_exposure() {+ fn tls_on_with_exposed_bind_flags_grpc_h2c_exposure() {let cfg = Config::from_toml_str(- "[tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n",+ "[server]\nbind_address = \"0.0.0.0\"\n\+ [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());}@@ -1736,6 +1830,148 @@ mod tests {}}+ // ── Cleartext network exposure: fail closed (issue #228) ─────────────────++ /// The whole point of #228: an operator who configures nothing gets a node+ /// only their own machine can reach. Before the fix this default was+ /// `0.0.0.0`, so a first `xerj` run published its admin API key in+ /// cleartext to every interface the host had.+ #[test]+ fn default_bind_is_loopback() {+ let cfg = Config::default();+ assert_eq!(cfg.server.bind_address, "127.0.0.1");+ assert!(cfg.bind_address_is_loopback());+ assert!(+ !cfg.tls.enabled,+ "TLS is off by default — that is the point"+ );+ assert!(+ !cfg.cleartext_exposed_off_loopback(),+ "a zero-config node must boot, not fail closed"+ );+ // An empty config file resolves to the same posture as no file.+ let from_toml = Config::from_toml_str("").unwrap();+ assert_eq!(from_toml.server.bind_address, "127.0.0.1");+ }++ /// Exposing every listener in cleartext must be stated, not stumbled into.+ /// `0.0.0.0` and `::` bind every interface; a link-local address is still+ /// reachable by every other host on the link; an unparseable address fails+ /// closed here and is rejected by the `SocketAddr` parse a moment later.+ #[test]+ fn cleartext_bind_off_loopback_trips_the_check() {+ for bind in [+ "0.0.0.0",+ "::",+ "10.0.0.7",+ "192.168.1.5",+ "fe80::1",+ "nope",+ ] {+ let cfg =+ Config::from_toml_str(&format!("[server]\nbind_address = \"{bind}\"\n")).unwrap();+ assert!(!cfg.tls.enabled);+ assert!(+ cfg.cleartext_exposed_off_loopback(),+ "{bind} with TLS off must trip"+ );+ }+ }++ /// Loopback binds are untouched — local development, the ES-YAML+ /// conformance harness and every `curl 127.0.0.1` quickstart keep working+ /// with TLS off. A fail-closed check that fires on the common case gets+ /// disabled wholesale.+ #[test]+ fn cleartext_bind_on_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")).unwrap();+ assert!(+ !cfg.cleartext_exposed_off_loopback(),+ "{bind} must not trip"+ );+ }+ }++ /// Every loopback spelling must produce a *bindable* address, not merely+ /// pass the loopback predicate. `format!("{bind}:{port}")` cannot express+ /// an IPv6 literal — `"::1:9200"` does not parse — so a `::1` node used to+ /// pass every check here and then die at bind time with `invalid socket+ /// address syntax`, after creating its data directory and printing a+ /// first-run console link. Making loopback the default (#228) makes `::1`+ /// a spelling people will now actually reach for.+ #[test]+ fn loopback_spellings_produce_bindable_addresses() {+ for bind in ["127.0.0.1", "::1", "[::1]", " ::1 "] {+ let cfg =+ Config::from_toml_str(&format!("[server]\nbind_address = \"{bind}\"\n")).unwrap();+ assert!(cfg.bind_address_is_loopback(), "{bind} should be loopback");+ let addr = cfg+ .socket_addr(9200)+ .unwrap_or_else(|| panic!("{bind} must yield a socket address"));+ assert!(addr.ip().is_loopback());+ assert_eq!(addr.port(), 9200);+ }+ assert_eq!(+ Config::from_toml_str("[server]\nbind_address = \"::1\"\n")+ .unwrap()+ .socket_addr(9200)+ .unwrap()+ .to_string(),+ "[::1]:9200"+ );+ }++ /// A bind address that is not an IP has no socket address to offer, and+ /// says so rather than producing something that fails later.+ #[test]+ fn non_ip_bind_has_no_socket_addr() {+ let cfg = Config::from_toml_str("[server]\nbind_address = \"example.com\"\n").unwrap();+ assert!(cfg.bind_ip().is_none());+ assert!(cfg.socket_addr(9200).is_none());+ assert!(!cfg.bind_address_is_loopback(), "must fail closed");+ }++ /// The escape hatch for proxy/sidecar/mesh TLS termination and for+ /// container images, whose network namespace is the boundary.+ #[test]+ fn declared_insecure_bind_permits_the_exposure() {+ let cfg = Config::from_toml_str(+ "[server]\nbind_address = \"0.0.0.0\"\nallow_insecure_network_bind = true\n",+ )+ .unwrap();+ assert!(!cfg.cleartext_exposed_off_loopback());+ }++ /// With TLS on, REST and ES-compat are encrypted and this check has+ /// nothing to say — the residual gRPC h2c exposure is #229's job. The two+ /// predicates partition on `tls.enabled`, so they can never both fire.+ #[test]+ fn tls_on_is_the_other_checks_business() {+ let cfg = Config::from_toml_str(+ "[server]\nbind_address = \"0.0.0.0\"\n\+ [tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n",+ )+ .unwrap();+ assert!(!cfg.cleartext_exposed_off_loopback());+ assert!(cfg.grpc_h2c_exposed_off_loopback());+ assert!(!(cfg.cleartext_exposed_off_loopback() && cfg.grpc_h2c_exposed_off_loopback()));+ }++ /// `allow_insecure_network_bind` relaxes only the cleartext check. It must+ /// not become a way to smuggle past #229's gRPC refusal as well, or one+ /// opt-out silently buys two exposures.+ #[test]+ fn insecure_bind_opt_out_does_not_relax_the_grpc_check() {+ let cfg = Config::from_toml_str(+ "[server]\nbind_address = \"0.0.0.0\"\nallow_insecure_network_bind = true\n\+ [tls]\nenabled = true\ncert_path = \"/c.pem\"\nkey_path = \"/k.pem\"\n",+ )+ .unwrap();+ assert!(cfg.grpc_h2c_exposed_off_loopback());+ }+// ── Cluster auth: fail closed (issue #75) ────────────────────────────────#[test]diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsindex e26d553ec..6fc3ca85a 100644--- a/engine/crates/xerj-server/src/grpc.rs+++ b/engine/crates/xerj-server/src/grpc.rs@@ -338,7 +338,8 @@ impl XerjSearch for GrpcService {/// shared [`xerj_api::auth::is_authorized`] decision. Without it the gRPC/// listener was fully unauthenticated even with `auth.enabled = true`: any/// client on the network could read, write, and delete documents (the listener-/// binds `server.bind_address`, default `0.0.0.0`).+/// binds `server.bind_address`, which since issue #228 defaults to loopback —+/// but is `0.0.0.0` in every deployment that exposes the node at all).////// The credential is read from the `authorization` request metadata/// (`ApiKey <key>` or `Bearer <key>`), mirroring the HTTP `Authorization`diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 69d208de9..f06b51fd0 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -106,6 +106,7 @@ mod ingest_memory_trace;struct CliArgs {config: Option<PathBuf>,data_dir: Option<String>,+ bind: Option<String>,insecure: bool,embed_mode: Option<String>,onnx_model: Option<String>,@@ -118,6 +119,7 @@ fn parse_args() -> CliArgs {let mut args = std::env::args().skip(1);let mut config = None;let mut data_dir = None;+ let mut bind = None;let mut insecure = false;let mut embed_mode = None;let mut onnx_model = None;@@ -133,6 +135,9 @@ fn parse_args() -> CliArgs {"--data-dir" | "-d" => {data_dir = args.next();}+ "--bind" | "-b" => {+ bind = args.next();+ }"--insecure" | "-k" => {insecure = true;}@@ -161,6 +166,7 @@ fn parse_args() -> CliArgs {CliArgs {config,data_dir,+ bind,insecure,embed_mode,onnx_model,@@ -180,6 +186,14 @@ fn print_help() {OPTIONS:\n\--config, -c <PATH> Path to TOML config file\n\--data-dir, -d <PATH> Override data directory\n\+ --bind, -b <ADDR> Interface to bind every listener to. Default 127.0.0.1 —\n\+ loopback only, reachable from this machine and nowhere\n\+ else. Pass 0.0.0.0 (or a specific address) to expose the\n\+ node; with TLS off that also needs\n\+ server.allow_insecure_network_bind = true (or\n\+ XERJ_ALLOW_INSECURE_NETWORK_BIND=true), because every\n\+ request — API key included — would cross the network in\n\+ cleartext. Env: XERJ_BIND_ADDRESS\n\--insecure, -k Disable TLS\n\--embed-mode <MODE> Embedding backend: lexical | neural | proxy | auto |\n\onnx-experimental\n\@@ -265,6 +279,27 @@ fn print_help() {// Startup banner// ─────────────────────────────────────────────────────────────────────────────+/// Why a bind address could not be turned into a listener. One message for all+/// three listeners: they share the one setting, so three different phrasings of+/// the same fault would only obscure it.+fn bad_bind_address(cfg: &Config) -> String {+ format!(+ "server.bind_address = {:?} is not an IP address — it must be an IPv4 or \+ IPv6 literal such as \"127.0.0.1\" (the default), \"0.0.0.0\" or \"::1\". \+ Host names are not resolved.",+ cfg.server.bind_address+ )+}++/// `bind_address` in a form that can be pasted into a URL: IPv6 literals need+/// brackets (`http://[::1]:9200`), IPv4 and host names do not.+fn url_host(bind: &str) -> String {+ match bind.trim().parse::<std::net::IpAddr>() {+ Ok(std::net::IpAddr::V6(v6)) => format!("[{v6}]"),+ _ => bind.trim().to_string(),+ }+}+fn print_banner(cfg: &Config, startup_ms: u128) {let tls = if cfg.tls.enabled { "TLS " } else { "plain" };println!();@@ -280,14 +315,24 @@ fn print_banner(cfg: &Config, startup_ms: u128) {println!();println!(" the unified search engine for AI — connect, autoindex, query");println!();- println!(" Native REST :{} [{}]", cfg.server.rest_port, tls);- println!(" ES-compat :{} [{}]", cfg.server.es_compat_port, tls);+ // The bind address belongs on every listener line (issue #228). Printing+ // bare `:9200` left the one fact that decides who can reach this node off+ // the only screen most operators ever read, and made a loopback-bound node+ // and a world-bound node look identical.+ // Bracketed for IPv6 so `host:port` stays unambiguous.+ let bind_hostport = url_host(&cfg.server.bind_address);+ let bind = bind_hostport.as_str();+ println!(" Native REST {}:{} [{}]", bind, cfg.server.rest_port, tls);+ println!(+ " ES-compat {}:{} [{}]",+ bind, cfg.server.es_compat_port, tls+ );// 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+ " gRPC {}:{} [h2c — plaintext, no TLS]",+ bind, cfg.server.grpc_port);println!(" Data dir {}", cfg.server.data_dir);println!(" Started in {}ms", startup_ms);@@ -306,6 +351,21 @@ fn print_banner(cfg: &Config, startup_ms: u128) {// an operator sees it on every start. Suppress nothing — these lines// map 1:1 to items on the path-to-100% plan.println!(" ┌─ Deployment posture (see PATH_TO_100_PCT_v0.6.0_to_v1.0.md) ──");+ // Reach, before anything else: it decides whether the rest of this block+ // is a local-development note or a production exposure (issue #228).+ if cfg.bind_address_is_loopback() {+ println!(" │ ✓ Bind: {bind} — loopback only; nothing off this host can reach the");+ println!(" │ listeners. Pass --bind 0.0.0.0 to expose the node.");+ } else if !cfg.tls.enabled {+ // Reaching here means the operator set the opt-out, so say what it+ // bought them rather than printing a generic warning.+ println!(" │ ⚠ Bind: {bind} — network-reachable AND TLS is off. API keys and");+ println!(" │ document bodies cross the network in cleartext, allowed by");+ println!(" │ server.allow_insecure_network_bind (issue #228). Terminate");+ println!(" │ TLS in front of this node, or bind loopback.");+ } else {+ println!(" │ ⚠ Bind: {bind} — network-reachable on every listed port.");+ }if !cfg.tls.enabled {println!(" │ ⚠ TLS: listener is plain TCP — terminate TLS at a reverse proxy");println!(" │ (or enable in-process TLS: tls.enabled = true)");@@ -364,6 +424,42 @@ fn load_config(args: &CliArgs) -> Result<Config> {cfg.server.data_dir = dir.clone();}+ // Bind address override: `--bind` flag or `XERJ_BIND_ADDRESS` env (flag+ // wins). Both exist because the default is loopback (#228): without a way+ // to say "expose me" that is not a TOML file, a container image or a+ // one-off `xerj -b 0.0.0.0` would have no path at all.+ if let Some(addr) = args+ .bind+ .clone()+ .or_else(|| std::env::var("XERJ_BIND_ADDRESS").ok())+ {+ let addr = addr.trim().to_string();+ if addr.is_empty() {+ anyhow::bail!("--bind / XERJ_BIND_ADDRESS is empty; pass an IP address");+ }+ info!("server.bind_address = {addr} (from CLI/env)");+ cfg.server.bind_address = addr;+ }++ // The #228 opt-out, also settable from the environment so a container can+ // declare its exposure without shipping a config file. Parsed strictly: a+ // value we cannot read is refused rather than treated as `false`, because+ // silently falling back to the safe value here means a boot that refuses+ // with a message about a setting the operator believes they set.+ if let Ok(raw) = std::env::var("XERJ_ALLOW_INSECURE_NETWORK_BIND") {+ let v = raw.trim();+ let parsed = match v.to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => true,+ "0" | "false" | "no" | "off" => false,+ _ => anyhow::bail!(+ "XERJ_ALLOW_INSECURE_NETWORK_BIND={raw:?} is not a boolean; \+ use true or false"+ ),+ };+ info!("server.allow_insecure_network_bind = {parsed} (from env)");+ cfg.server.allow_insecure_network_bind = parsed;+ }+if args.insecure {warn!("--insecure: TLS and auth disabled");cfg.tls.enabled = false;@@ -979,6 +1075,9 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {let fake_cli = CliArgs {config: cmd.config.clone(),data_dir: cmd.data_dir.clone(),+ // In-process CLI indexing binds no listener at all, so the bind+ // address is irrelevant here — take whatever the config says.+ bind: None,insecure: true,embed_mode: None,onnx_model: None,@@ -1640,6 +1739,40 @@ async fn async_main() -> Result<()> {);}+ // 3c. Cleartext network exposure — fail closed (issue #228). The TLS-off+ // twin of 3b, and the larger of the two: with `tls.enabled = false`+ // it is not one uncovered listener but every listener, carrying the+ // `Authorization: ApiKey` header of every request in the clear.+ //+ // Auth being on by default does not help. It is precisely the+ // credential that is on the wire, and it is on the wire on every+ // interface the host happens to have — which used to include whatever+ // the machine picked up from DHCP, because `0.0.0.0` was the default+ // bind. That default is now loopback, so this fires only for a bind+ // that someone actually wrote down, and it asks them to write down+ // the consequence too.+ //+ // Placed with 3b, before the data directory, the first-run admin key+ // and the certificate, so a rejected boot leaves nothing behind.+ if cfg.cleartext_exposed_off_loopback() {+ anyhow::bail!(+ "server.bind_address = \"{}\" is not loopback and tls.enabled = false, so every \+ listener ({}, {}, {}) would serve plain HTTP on a network-reachable interface — \+ the API key in every Authorization header, and every document body, would cross \+ the network in cleartext. Refusing to start. Fix by binding to loopback \+ (server.bind_address = \"127.0.0.1\", the default) and putting a proxy in front, \+ or by enabling TLS (tls.enabled = true with cert_path + key_path). If something \+ already terminates TLS in front of this node — reverse proxy, sidecar, service \+ mesh, ingress, or a container network namespace — declare it: \+ server.allow_insecure_network_bind = true (env: \+ XERJ_ALLOW_INSECURE_NETWORK_BIND=true).",+ cfg.server.bind_address,+ cfg.server.rest_port,+ cfg.server.es_compat_port,+ cfg.server.grpc_port,+ );+ }+// 4. Data directorystd::fs::create_dir_all(&cfg.server.data_dir).with_context(|| format!("create data dir {}", cfg.server.data_dir))?;@@ -1756,9 +1889,12 @@ async fn async_main() -> Result<()> {let xerj_console_bind_url = format!("http://{}:{}",if cfg.server.bind_address == "0.0.0.0" || cfg.server.bind_address == "::" {- "localhost"+ "localhost".to_string()} else {- cfg.server.bind_address.as_str()+ // Bracketed for IPv6 — an unbracketed `http://::1:9200/…` is not a+ // URL any browser will open, and this string is printed in the+ // first-launch console link.+ url_host(&cfg.server.bind_address)},cfg.server.es_compat_port,);@@ -1837,17 +1973,19 @@ async fn async_main() -> Result<()> {info!("startup complete in {}ms", startup_ms);print_banner(&cfg, startup_ms);- // 11. Bind addresses- let bind = &cfg.server.bind_address;- let rest_addr: SocketAddr = format!("{}:{}", bind, cfg.server.rest_port)- .parse()- .context("parse REST bind address")?;- let es_addr: SocketAddr = format!("{}:{}", bind, cfg.server.es_compat_port)- .parse()- .context("parse ES-compat bind address")?;- let grpc_addr: SocketAddr = format!("{}:{}", bind, cfg.server.grpc_port)- .parse()- .context("parse gRPC bind address")?;+ // 11. Bind addresses. Composed from the parsed IP, never by formatting+ // `"{bind}:{port}"` — that string is unparseable for every IPv6+ // literal (`"::1:9200"`), which made `bind_address = "::1"` a node+ // that could not start at all.+ let rest_addr: SocketAddr = cfg+ .socket_addr(cfg.server.rest_port)+ .with_context(|| bad_bind_address(&cfg))?;+ let es_addr: SocketAddr = cfg+ .socket_addr(cfg.server.es_compat_port)+ .with_context(|| bad_bind_address(&cfg))?;+ let grpc_addr: SocketAddr = cfg+ .socket_addr(cfg.server.grpc_port)+ .with_context(|| bad_bind_address(&cfg))?;// 12. Background flush timerlet flusher = spawn_periodic_flusher(diff --git a/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs b/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rsnew file mode 100644index 000000000..fa9e1d70a--- /dev/null+++ b/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs@@ -0,0 +1,413 @@+//! Issue #228: a cleartext node must not publish itself to the network.+//!+//! TLS is off by default. A `server.bind_address` that is not loopback+//! therefore puts every listener — and the `Authorization: ApiKey` header of+//! every request that reaches them — on the wire in the clear. The REAL binary+//! must exit non-zero before binding anything unless the operator has said the+//! exposure is intended.+//!+//! Why a process-level test and not only the unit tests on+//! `Config::cleartext_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` (plus `extra_args`) and return+/// `(success, stderr)`.+///+/// The fixed binary rejects at step 3c of startup — before the data directory,+/// the first-run admin key, 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, extra_args: &[&str]) -> (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)+ .args(extra_args)+ .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 a non-loopback bind_address and tls.enabled \+ = false — it is serving plain HTTP on a network-reachable interface, \+ so every API key it accepts crosses the wire in cleartext"+ );+ }+ 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)+}++/// Build a config body binding `bind` on three free ports under `dir`.+fn config_for(bind: &str, dir: &std::path::Path, ports: (u16, u16, u16)) -> String {+ let (rest, grpc, es) = ports;+ format!(+ r#"+[server]+bind_address = "{bind}"+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"+"#,+ data = toml_path(&dir.join("data")),+ )+}++/// `0.0.0.0` binds every interface the host has. With TLS off — the default —+/// that publishes the admin API key in cleartext to all of them. This is the+/// assertion that fails without the fix.+#[test]+fn cleartext_bind_on_every_interface_refuses_to_start() {+ let dir = tempfile::tempdir().unwrap();+ let data_dir = dir.path().join("data");+ let ports = three_free_ports();++ let (ok, stderr) = run_until_exit(&config_for("0.0.0.0", dir.path(), ports), dir.path(), &[]);++ assert!(+ !ok,+ "a non-loopback bind with TLS off must exit non-zero; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("cleartext") && stderr.contains("Refusing to start"),+ "the exit reason must name the exposure and the refusal; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("server.allow_insecure_network_bind"),+ "the operator must be told the setting that unblocks the boot, or the \+ refusal is a dead end; stderr:\n{stderr}"+ );+ // Refused at step 3c, before anything is created: no data directory, no+ // first-run admin key minted and printed. A rejected boot that still seeds+ // credentials leaves state to clean up — and an admin key on stdout that+ // was never actually used.+ assert!(+ !data_dir.exists(),+ "a rejected boot must not create the data dir; stderr:\n{stderr}"+ );+}++/// A private-network address is no more encrypted than a public one, and+/// `--insecure` drops authentication on top — which the shipped docs already+/// claimed refuses to run off-loopback while the binary happily served+/// unauthenticated writes to the LAN.+#[test]+fn insecure_flag_does_not_buy_a_network_bind() {+ let dir = tempfile::tempdir().unwrap();+ let ports = three_free_ports();++ let (ok, stderr) = run_until_exit(+ &config_for("10.0.0.7", dir.path(), ports),+ dir.path(),+ &["--insecure"],+ );++ assert!(+ !ok,+ "--insecure clears tls.enabled, so it must trip the check rather than \+ evade it; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("10.0.0.7"),+ "the refusal must quote the offending bind address; stderr:\n{stderr}"+ );+}++/// The default posture has to boot. `xerj` with no `[server]` block at all is+/// the first thing anyone runs, and the fix is worthless if it turns that into+/// a startup failure.+#[test]+fn default_and_loopback_binds_start_normally() {+ for bind in [None, Some("127.0.0.1"), Some("::1")] {+ let dir = tempfile::tempdir().unwrap();+ let (rest, grpc, es) = three_free_ports();+ let bind_line = match bind {+ Some(b) => format!("bind_address = \"{b}\"\n"),+ None => String::new(),+ };+ let config_path = dir.path().join("xerj.toml");+ std::fs::write(+ &config_path,+ format!(+ r#"+[server]+{bind_line}rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"+"#,+ data = toml_path(&dir.path().join("data")),+ ),+ )+ .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 3c.+ 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,+ "bind {bind:?} must start; it exited instead. stderr:\n{stderr}"+ );+ assert!(+ !stderr.contains("Refusing to start"),+ "the cleartext check must not fire on loopback; stderr:\n{stderr}"+ );+ }+}++/// The documented escape hatch has to actually work, or operators will reach+/// for something worse to get past the refusal. Asserted through the+/// environment variable specifically, because that is the path a container+/// image and the Helm chart take — a config key they cannot reach would make+/// the default change unshippable for Docker and Kubernetes.+///+/// Binds loopback so the test starts no publicly reachable listener; the+/// opt-out is what is under test, and the non-loopback half of the matrix is+/// covered by the unit tests in `xerj-common::config`.+#[test]+fn declared_exposure_is_accepted_from_config_and_env() {+ let dir = tempfile::tempdir().unwrap();+ 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"+allow_insecure_network_bind = true+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"+"#,+ data = toml_path(&dir.path().join("data")),+ ),+ )+ .unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .env("XERJ_ALLOW_INSECURE_NETWORK_BIND", "true")+ .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,+ "allow_insecure_network_bind must be accepted as a config key and as \+ XERJ_ALLOW_INSECURE_NETWORK_BIND, and must not block startup. \+ stderr:\n{stderr}"+ );+}++/// A knob the binary accepts but will not honour is the bug class tracked in+/// #204. `XERJ_ALLOW_INSECURE_NETWORK_BIND=maybe` is not a boolean, and+/// treating it as `false` would refuse the boot with a message naming a+/// setting the operator believes they already set.+#[test]+fn unparseable_opt_out_env_fails_loudly() {+ let dir = tempfile::tempdir().unwrap();+ 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}"+"#,+ data = toml_path(&dir.path().join("data")),+ ),+ )+ .unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .env("XERJ_ALLOW_INSECURE_NETWORK_BIND", "maybe")+ .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!("a non-boolean XERJ_ALLOW_INSECURE_NETWORK_BIND was silently ignored");+ }+ 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(), "must exit non-zero; stderr:\n{stderr}");+ assert!(+ stderr.contains("XERJ_ALLOW_INSECURE_NETWORK_BIND"),+ "the error must name the variable it could not read; stderr:\n{stderr}"+ );+}++/// `--bind` exists only because the default is loopback: without it there is+/// no way to expose the node other than writing a TOML file. If the flag were+/// parsed but not applied, the default change would look like a hard+/// regression to anyone who reached for the obvious flag.+#[test]+fn bind_flag_is_honoured_and_still_gated() {+ let dir = tempfile::tempdir().unwrap();+ let (rest, grpc, es) = three_free_ports();+ let config_path = dir.path().join("xerj.toml");+ std::fs::write(+ &config_path,+ format!(+ r#"+[server]+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"+"#,+ data = toml_path(&dir.path().join("data")),+ ),+ )+ .unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .arg("--bind")+ .arg("10.0.0.7")+ .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!(+ "--bind 10.0.0.7 was accepted but not applied — the config file's \+ loopback default survived, so the flag is inert"+ );+ }+ 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(), "must exit non-zero; stderr:\n{stderr}");+ assert!(+ stderr.contains("10.0.0.7"),+ "the refusal must quote the address --bind supplied, proving the flag \+ reached the config; stderr:\n{stderr}"+ );+}diff --git a/engine/docker-compose.yml b/engine/docker-compose.ymlindex 542a32e56..7994597fa 100644--- a/engine/docker-compose.yml+++ b/engine/docker-compose.yml@@ -13,6 +13,14 @@ services:- xerj-data:/dataenvironment:XERJ_LOG: info+ # The image already sets both (see Dockerfile): xerj defaults to a+ # loopback bind, which inside a container means nothing published on+ # `ports:` above would ever answer. Repeated here so the exposure is+ # visible in the file you actually edit — the published ports are+ # cleartext HTTP, so put TLS in front of them before this leaves a+ # trusted network.+ XERJ_BIND_ADDRESS: "0.0.0.0"+ XERJ_ALLOW_INSECURE_NETWORK_BIND: "true"command: ["--data-dir", "/data"]volumes:diff --git a/engine/xerj.default.toml b/engine/xerj.default.tomlindex 952ce0b1f..2ad60e7c8 100644--- a/engine/xerj.default.toml+++ b/engine/xerj.default.toml@@ -11,7 +11,7 @@# every default below.# ============================================================-# ── Network & Data Directory (6 settings) ─────────────────────────────────────+# ── Network & Data Directory (7 settings) ─────────────────────────────────────[server]@@ -32,8 +32,32 @@ es_compat_port = 9200data_dir = "./data"# IP address to bind all listeners to.-# "0.0.0.0" listens on all interfaces; use "127.0.0.1" for localhost only.-bind_address = "0.0.0.0"+#+# Defaults to loopback: a fresh node is reachable from the machine it runs on+# and nowhere else. TLS is off by default, so a node that bound every interface+# out of the box would put its admin API key and every document body on the+# network in cleartext, and a working curl would give no hint of it.+#+# Set "0.0.0.0" (every interface) or a specific private address to expose the+# node. With tls.enabled = false that also requires+# allow_insecure_network_bind = true below — xerj refuses to start otherwise.+# Overridable without this file: --bind 0.0.0.0 or XERJ_BIND_ADDRESS=0.0.0.0.+bind_address = "127.0.0.1"++# Allow a network-reachable bind_address while TLS is off. Default false,+# which REFUSES TO START in that combination: every listener would serve plain+# HTTP, so the Authorization: ApiKey header of every request crosses the+# network in the clear.+#+# Set true only when something in front of this node terminates TLS — reverse+# proxy, sidecar, service mesh, ingress controller — or when the link itself+# is trusted. Container images set it because the container's own network+# namespace is the boundary; the published port is where you add TLS.+#+# Binding loopback needs no opt-out, and this is ignored when tls.enabled =+# true (there the residual gRPC exposure is allow_insecure_grpc_h2c's job).+# Env: XERJ_ALLOW_INSECURE_NETWORK_BIND=true+allow_insecure_network_bind = false# Reverse proxies whose X-Forwarded-For / X-Real-IP headers may be believed.#diff --git a/landing/docs/cli.html b/landing/docs/cli.htmlindex d2e51af2f..5b5b41178 100644--- a/landing/docs/cli.html+++ b/landing/docs/cli.html@@ -128,6 +128,8 @@ OPTIONS:-c, --config <PATH> Path to the TOML config file[default: ./xerj.toml]-d, --data-dir <PATH> Override [server] data_dir+ -b, --bind <ADDR> Override [server] bind_address+ [default: 127.0.0.1 — loopback only]-k, --insecure Disable TLS and API-key auth (dev only)-h, --help Print help-V, --version Print version and build commit</pre>@@ -138,8 +140,11 @@ OPTIONS:<h2 id="data-dir-flag">--data-dir / -d</h2><p>Convenience override for <code class="inline">[server] data_dir</code>. Useful for ephemeral dev runs and for pointing XERJ at a tmpfs when you just want to burn something down after.</p>+ <h2 id="bind-flag">--bind / -b</h2>+ <p>Interface to bind every listener to; overrides <code class="inline">[server] bind_address</code>. Env: <code class="inline">XERJ_BIND_ADDRESS</code>. The default is <code class="inline">127.0.0.1</code> — loopback only. Pass <code class="inline">0.0.0.0</code> (or a specific address) to expose the node; with TLS off that also needs <code class="inline">server.allow_insecure_network_bind = true</code> (env <code class="inline">XERJ_ALLOW_INSECURE_NETWORK_BIND</code>), because every request, API key included, would cross the network in cleartext.</p>+<h2 id="insecure-flag">--insecure / -k</h2>- <p>Disables TLS and API-key auth. <strong>Dev only.</strong> Fails loudly in production by refusing to start if <code class="inline">bind_address</code> is anything other than <code class="inline">127.0.0.1</code> unless the binary is built with the <code class="inline">--release-mode dev</code> flag.</p>+ <p>Disables TLS and API-key auth. <strong>Dev only.</strong> It does not unlock a network bind: clearing <code class="inline">tls.enabled</code> is exactly what makes a non-loopback <code class="inline">bind_address</code> refuse to start, so <code class="inline">--insecure</code> on <code class="inline">0.0.0.0</code> exits non-zero unless the exposure is declared.</p><h2>--help / -h</h2><p>Prints the synopsis above and exits.</p>diff --git a/landing/docs/config.html b/landing/docs/config.htmlindex d6e9b7363..e829e57fa 100644--- a/landing/docs/config.html+++ b/landing/docs/config.html@@ -124,7 +124,7 @@<p>Paths for the config are, in precedence order: <code class="inline">--config /path/to/xerj.toml</code> on the command line, then <code class="inline">/etc/xerj/xerj.toml</code>, then <code class="inline">./xerj.toml</code> in the working directory. If none exist, the full default is used.</p><h2>Full key table</h2>- <div class="cfg"><div class="head">KEY</div><div class="head">TYPE</div><div class="head">DEFAULT</div><div class="head">DESCRIPTION</div><div class="group" id="server">[server]</div><div class="cell k">rest_port</div><div class="cell t">u16</div><div class="cell d">8080</div><div class="cell dsc">Native REST API listener port. All native endpoints (/v1/*) live here.</div><div class="cell k">grpc_port</div><div class="cell t">u16</div><div class="cell d">8081</div><div class="cell dsc">Reserved for a future gRPC API. Not wired in v0.1 — leave at default.</div><div class="cell k">es_compat_port</div><div class="cell t">u16</div><div class="cell d">9200</div><div class="cell dsc">Elasticsearch-compatible wire port. Point Kibana, Logstash, or the ES client here. Set to 0 to disable.</div><div class="cell k">bind_address</div><div class="cell t">string</div><div class="cell d">"0.0.0.0"</div><div class="cell dsc">Interface to bind every listener to. Use "127.0.0.1" for dev or a private address in production.</div><div class="cell k">data_dir</div><div class="cell t">path</div><div class="cell d">"./data"</div><div class="cell dsc">Root for indices, WAL files, and segments. Needs fast I/O and enough free space.</div><div class="group" id="auth">[auth]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Require an API key on every request. Set to false only on a trusted network.</div><div class="cell k">admin_api_key</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Static admin key. Left empty, a 256-bit key is generated on first run and written to <data_dir>/admin.key.</div><div class="group" id="tls">[tls]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Terminate TLS at the server. Requires cert_path + key_path. If you terminate at a proxy, leave false.</div><div class="cell k">cert_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM X.509 certificate. Use a CA-signed cert in production.</div><div class="cell k">key_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM private key. Permissions should be 0600.</div><div class="group" id="storage">[storage]</div><div class="cell k">wal_sync</div><div class="cell t">enum</div><div class="cell d">"batched"</div><div class="cell dsc">"sync" · "batched" · "async". Durability vs throughput. Batched is the recommended default.</div><div class="cell k">wal_batch_ms</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Fsync cadence when wal_sync="batched" (ms). Range 1–10000. Lower = smaller loss window.</div><div class="cell k">wal_max_size_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">WAL rollover threshold (MiB). Larger means fewer rollovers, longer crash recovery.</div><div class="cell k">flush_size_mb</div><div class="cell t">u32</div><div class="cell d">256</div><div class="cell dsc">Memtable buffer size that triggers a segment flush (MiB).</div><div class="cell k">flush_interval_secs</div><div class="cell t">u32</div><div class="cell d">30</div><div class="cell dsc">Maximum wall-clock interval between flushes even if the buffer is not full.</div><div class="group" id="merge">[merge]</div><div class="cell k">strategy</div><div class="cell t">enum</div><div class="cell d">"size_tiered"</div><div class="cell dsc">"size_tiered" or "log_structured". Size-tiered for write-heavy, log-structured for mixed workloads.</div><div class="cell k">min_segments</div><div class="cell t">u32</div><div class="cell d">10</div><div class="cell dsc">Minimum live segments before a merge pass is scheduled. Must be ≥ 2.</div><div class="cell k">max_segment_mb</div><div class="cell t">u32</div><div class="cell d">5120</div><div class="cell dsc">Upper bound on a mergeable segment (MiB). Segments larger than this are never merged.</div><div class="cell k">io_rate_mb_per_sec</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Merge I/O throttle (MiB/s). Set 0 to disable — not recommended in production.</div><div class="cell k">max_concurrent</div><div class="cell t">u8</div><div class="cell d">1</div><div class="cell dsc">Concurrent merge workers per index. Bump to 2–4 on fast NVMe.</div><div class="group" id="compression">[compression]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Block-level compression. Disabling increases disk usage and lowers read CPU.</div><div class="cell k">level</div><div class="cell t">enum</div><div class="cell d">"balanced"</div><div class="cell dsc">"fast" (LZ4), "balanced" (Zstd L3, default), "best" (Zstd L19, cold storage).</div><div class="cell k">block_size_docs</div><div class="cell t">u32</div><div class="cell d">128</div><div class="cell dsc">Docs per compressed block. Range 16–4096. Larger = better ratio, higher fetch cost.</div><div class="group" id="fts">[fts]</div><div class="cell k">default_analyzer</div><div class="cell t">enum</div><div class="cell d">"standard"</div><div class="cell dsc">"standard" · "whitespace" · "simple" · "english". Override per-field in the mapping.</div><div class="group" id="vector">[vector]</div><div class="cell k">default_metric</div><div class="cell t">enum</div><div class="cell d">"cosine"</div><div class="cell dsc">"cosine" · "dot_product" · "euclidean". Cosine for text embeddings is the usual choice.</div><div class="cell k">hnsw_m</div><div class="cell t">u32</div><div class="cell d">16</div><div class="cell dsc">Accepted and validated; the built-in HNSW graph currently builds with fixed M=16 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_construction</div><div class="cell t">u32</div><div class="cell d">200</div><div class="cell dsc">Accepted; must be ≥ hnsw_m. The graph currently builds with fixed ef_construction=200 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_search</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but not read by the serving path — the ANN beam width comes from the request's num_candidates (floored at 800).</div><div class="cell k">default_quantization</div><div class="cell t">enum</div><div class="cell d">"scalar8"</div><div class="cell dsc">"none" · "scalar8" · "scalar4" · "binary". scalar8 = 4× RAM saving, 1–2% recall loss.</div><div class="cell k">max_dimensions</div><div class="cell t">u32</div><div class="cell d">16384</div><div class="cell dsc">Upper bound on vector dimensionality. 4× the Elasticsearch limit of 4096.</div><div class="group" id="logs">[logs]</div><div class="cell k">retention_days</div><div class="cell t">u32</div><div class="cell d">90</div><div class="cell dsc">Auto-delete log docs older than N days. 0 disables.</div><div class="cell k">time_partition</div><div class="cell t">enum</div><div class="cell d">"1h"</div><div class="cell dsc">"1m" · "5m" · "15m" · "1h" · "6h" · "1d". Time-slice granularity for retention pruning.</div><div class="group" id="embedding">[embedding]</div><div class="cell k">default_endpoint</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">OpenAI-compatible embeddings URL. Empty disables auto-embedding on ingest. Example: "https://api.openai.com/v1/embeddings".</div><div class="cell k">default_model</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Model name passed to the endpoint. Example: "text-embedding-3-small" or "nomic-embed-text".</div><div class="cell k">batch_size</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Docs per embedding API call. Range 1–2048. Bigger batches amortise round-trip cost.</div><div class="cell k">timeout_ms</div><div class="cell t">u32</div><div class="cell d">5000</div><div class="cell dsc">HTTP timeout for embedding calls (ms). Ingest fails with a timeout error if exceeded.</div><div class="group" id="limits">[limits]</div><div class="cell k">max_query_memory_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Per-query memory cap (MiB). Queries that exceed it are cancelled.</div><div class="cell k">max_concurrent_searches</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Global in-flight search ceiling. Extras are queued.</div><div class="cell k">max_fields_per_index</div><div class="cell t">u32</div><div class="cell d">500</div><div class="cell dsc">Field-explosion protection. ES default is 1000; 500 is intentionally stricter.</div><div class="group" id="indexing">[indexing]</div><div class="cell k">turbo_batch_size</div><div class="cell t">u32</div><div class="cell d">1000</div><div class="cell dsc">Docs per batch in turbo mode. Range 500–5000. Larger = higher throughput, slightly higher latency.</div><div class="cell k">turbo_parallel</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Parallel tokenisation on Rayon threads. Disable only for debugging.</div><div class="cell k">turbo_fast_analyzer</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Skip stemming and stop-word removal in turbo mode. Trades recall for speed.</div><div class="group" id="cluster">[cluster]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Enable multi-node cluster mode. When true, the Raft state machine and cluster transport are started on port.</div><div class="cell k">port</div><div class="cell t">u16</div><div class="cell d">9300</div><div class="cell dsc">TCP port for intra-cluster Raft and search messages. Must be reachable from every peer.</div><div class="cell k">peers</div><div class="cell t">array</div><div class="cell d">[]</div><div class="cell dsc">Peer list in "node_id=host:port" format. The local node identifies itself from the entry matching bind_address:port. Example: ["a=10.0.0.1:9300","b=10.0.0.2:9300","c=10.0.0.3:9300"].</div><div class="cell k">tick_ms</div><div class="cell t">u64</div><div class="cell d">50</div><div class="cell dsc">Raft tick interval (ms). Lower = faster leader election at the cost of CPU.</div><div class="cell k">auth_secret</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Cluster-wide shared secret authenticating every control frame on port (HMAC-SHA256 over a per-connection challenge). Mandatory when enabled = true — with cluster mode on and no secret here or in XERJ_CLUSTER_AUTH_SECRET the node refuses to start. Same value on every node; minimum 16 chars; generate with `openssl rand -hex 32`. Authenticates, does not encrypt.</div></div>+ <div class="cfg"><div class="head">KEY</div><div class="head">TYPE</div><div class="head">DEFAULT</div><div class="head">DESCRIPTION</div><div class="group" id="server">[server]</div><div class="cell k">rest_port</div><div class="cell t">u16</div><div class="cell d">8080</div><div class="cell dsc">Native REST API listener port. All native endpoints (/v1/*) live here.</div><div class="cell k">grpc_port</div><div class="cell t">u16</div><div class="cell d">8081</div><div class="cell dsc">Reserved for a future gRPC API. Not wired in v0.1 — leave at default.</div><div class="cell k">es_compat_port</div><div class="cell t">u16</div><div class="cell d">9200</div><div class="cell dsc">Elasticsearch-compatible wire port. Point Kibana, Logstash, or the ES client here. Set to 0 to disable.</div><div class="cell k">bind_address</div><div class="cell t">string</div><div class="cell d">"127.0.0.1"</div><div class="cell dsc">Interface to bind every listener to. Loopback by default, so an unconfigured node is unreachable from the network. Set "0.0.0.0" or a private address to expose it (also --bind / XERJ_BIND_ADDRESS).</div><div class="cell k">allow_insecure_network_bind</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Permit a non-loopback bind_address while tls.enabled = false. Startup refuses that combination otherwise: every listener would serve plain HTTP, so the API key in every Authorization header crosses the network in cleartext. Set true only when a proxy, sidecar, mesh or container boundary terminates TLS in front of the node. Env: XERJ_ALLOW_INSECURE_NETWORK_BIND.</div><div class="cell k">data_dir</div><div class="cell t">path</div><div class="cell d">"./data"</div><div class="cell dsc">Root for indices, WAL files, and segments. Needs fast I/O and enough free space.</div><div class="group" id="auth">[auth]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Require an API key on every request. Set to false only on a trusted network.</div><div class="cell k">admin_api_key</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Static admin key. Left empty, a 256-bit key is generated on first run and written to <data_dir>/admin.key.</div><div class="group" id="tls">[tls]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Terminate TLS at the server. Requires cert_path + key_path. If you terminate at a proxy, leave false.</div><div class="cell k">cert_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM X.509 certificate. Use a CA-signed cert in production.</div><div class="cell k">key_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM private key. Permissions should be 0600.</div><div class="group" id="storage">[storage]</div><div class="cell k">wal_sync</div><div class="cell t">enum</div><div class="cell d">"batched"</div><div class="cell dsc">"sync" · "batched" · "async". Durability vs throughput. Batched is the recommended default.</div><div class="cell k">wal_batch_ms</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Fsync cadence when wal_sync="batched" (ms). Range 1–10000. Lower = smaller loss window.</div><div class="cell k">wal_max_size_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">WAL rollover threshold (MiB). Larger means fewer rollovers, longer crash recovery.</div><div class="cell k">flush_size_mb</div><div class="cell t">u32</div><div class="cell d">256</div><div class="cell dsc">Memtable buffer size that triggers a segment flush (MiB).</div><div class="cell k">flush_interval_secs</div><div class="cell t">u32</div><div class="cell d">30</div><div class="cell dsc">Maximum wall-clock interval between flushes even if the buffer is not full.</div><div class="group" id="merge">[merge]</div><div class="cell k">strategy</div><div class="cell t">enum</div><div class="cell d">"size_tiered"</div><div class="cell dsc">"size_tiered" or "log_structured". Size-tiered for write-heavy, log-structured for mixed workloads.</div><div class="cell k">min_segments</div><div class="cell t">u32</div><div class="cell d">10</div><div class="cell dsc">Minimum live segments before a merge pass is scheduled. Must be ≥ 2.</div><div class="cell k">max_segment_mb</div><div class="cell t">u32</div><div class="cell d">5120</div><div class="cell dsc">Upper bound on a mergeable segment (MiB). Segments larger than this are never merged.</div><div class="cell k">io_rate_mb_per_sec</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Merge I/O throttle (MiB/s). Set 0 to disable — not recommended in production.</div><div class="cell k">max_concurrent</div><div class="cell t">u8</div><div class="cell d">1</div><div class="cell dsc">Concurrent merge workers per index. Bump to 2–4 on fast NVMe.</div><div class="group" id="compression">[compression]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Block-level compression. Disabling increases disk usage and lowers read CPU.</div><div class="cell k">level</div><div class="cell t">enum</div><div class="cell d">"balanced"</div><div class="cell dsc">"fast" (LZ4), "balanced" (Zstd L3, default), "best" (Zstd L19, cold storage).</div><div class="cell k">block_size_docs</div><div class="cell t">u32</div><div class="cell d">128</div><div class="cell dsc">Docs per compressed block. Range 16–4096. Larger = better ratio, higher fetch cost.</div><div class="group" id="fts">[fts]</div><div class="cell k">default_analyzer</div><div class="cell t">enum</div><div class="cell d">"standard"</div><div class="cell dsc">"standard" · "whitespace" · "simple" · "english". Override per-field in the mapping.</div><div class="group" id="vector">[vector]</div><div class="cell k">default_metric</div><div class="cell t">enum</div><div class="cell d">"cosine"</div><div class="cell dsc">"cosine" · "dot_product" · "euclidean". Cosine for text embeddings is the usual choice.</div><div class="cell k">hnsw_m</div><div class="cell t">u32</div><div class="cell d">16</div><div class="cell dsc">Accepted and validated; the built-in HNSW graph currently builds with fixed M=16 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_construction</div><div class="cell t">u32</div><div class="cell d">200</div><div class="cell dsc">Accepted; must be ≥ hnsw_m. The graph currently builds with fixed ef_construction=200 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_search</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but not read by the serving path — the ANN beam width comes from the request's num_candidates (floored at 800).</div><div class="cell k">default_quantization</div><div class="cell t">enum</div><div class="cell d">"scalar8"</div><div class="cell dsc">"none" · "scalar8" · "scalar4" · "binary". scalar8 = 4× RAM saving, 1–2% recall loss.</div><div class="cell k">max_dimensions</div><div class="cell t">u32</div><div class="cell d">16384</div><div class="cell dsc">Upper bound on vector dimensionality. 4× the Elasticsearch limit of 4096.</div><div class="group" id="logs">[logs]</div><div class="cell k">retention_days</div><div class="cell t">u32</div><div class="cell d">90</div><div class="cell dsc">Auto-delete log docs older than N days. 0 disables.</div><div class="cell k">time_partition</div><div class="cell t">enum</div><div class="cell d">"1h"</div><div class="cell dsc">"1m" · "5m" · "15m" · "1h" · "6h" · "1d". Time-slice granularity for retention pruning.</div><div class="group" id="embedding">[embedding]</div><div class="cell k">default_endpoint</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">OpenAI-compatible embeddings URL. Empty disables auto-embedding on ingest. Example: "https://api.openai.com/v1/embeddings".</div><div class="cell k">default_model</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Model name passed to the endpoint. Example: "text-embedding-3-small" or "nomic-embed-text".</div><div class="cell k">batch_size</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Docs per embedding API call. Range 1–2048. Bigger batches amortise round-trip cost.</div><div class="cell k">timeout_ms</div><div class="cell t">u32</div><div class="cell d">5000</div><div class="cell dsc">HTTP timeout for embedding calls (ms). Ingest fails with a timeout error if exceeded.</div><div class="group" id="limits">[limits]</div><div class="cell k">max_query_memory_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Per-query memory cap (MiB). Queries that exceed it are cancelled.</div><div class="cell k">max_concurrent_searches</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Global in-flight search ceiling. Extras are queued.</div><div class="cell k">max_fields_per_index</div><div class="cell t">u32</div><div class="cell d">500</div><div class="cell dsc">Field-explosion protection. ES default is 1000; 500 is intentionally stricter.</div><div class="group" id="indexing">[indexing]</div><div class="cell k">turbo_batch_size</div><div class="cell t">u32</div><div class="cell d">1000</div><div class="cell dsc">Docs per batch in turbo mode. Range 500–5000. Larger = higher throughput, slightly higher latency.</div><div class="cell k">turbo_parallel</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Parallel tokenisation on Rayon threads. Disable only for debugging.</div><div class="cell k">turbo_fast_analyzer</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Skip stemming and stop-word removal in turbo mode. Trades recall for speed.</div><div class="group" id="cluster">[cluster]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Enable multi-node cluster mode. When true, the Raft state machine and cluster transport are started on port.</div><div class="cell k">port</div><div class="cell t">u16</div><div class="cell d">9300</div><div class="cell dsc">TCP port for intra-cluster Raft and search messages. Must be reachable from every peer.</div><div class="cell k">peers</div><div class="cell t">array</div><div class="cell d">[]</div><div class="cell dsc">Peer list in "node_id=host:port" format. The local node identifies itself from the entry matching bind_address:port. Example: ["a=10.0.0.1:9300","b=10.0.0.2:9300","c=10.0.0.3:9300"].</div><div class="cell k">tick_ms</div><div class="cell t">u64</div><div class="cell d">50</div><div class="cell dsc">Raft tick interval (ms). Lower = faster leader election at the cost of CPU.</div><div class="cell k">auth_secret</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Cluster-wide shared secret authenticating every control frame on port (HMAC-SHA256 over a per-connection challenge). Mandatory when enabled = true — with cluster mode on and no secret here or in XERJ_CLUSTER_AUTH_SECRET the node refuses to start. Same value on every node; minimum 16 chars; generate with `openssl rand -hex 32`. Authenticates, does not encrypt.</div></div><h2 id="server-section">[server]</h2>@@ -133,8 +133,10 @@rest_port = 8080 # native /v1/* APIes_compat_port = 9200 # ES wire-compatible APIgrpc_port = 8081 # reserved-bind_address = "0.0.0.0" # listen on all interfaces+bind_address = "0.0.0.0" # default is "127.0.0.1" (loopback only)+allow_insecure_network_bind = true # required for a non-loopback bind while TLS is offdata_dir = "/var/lib/xerj" # absolute path is strongly recommended</pre>+ <p>The default bind is loopback, so an unconfigured node is not reachable from the network. Exposing it while <code class="inline">tls.enabled = false</code> refuses to start unless <code class="inline">allow_insecure_network_bind</code> says the cleartext exposure is intended — enable TLS and neither line is needed.</p><h2 id="auth-section">[auth]</h2><p>Static API-key authentication. The first-run admin key is written to <code class="inline"><data_dir>/admin.key</code>; subsequent starts reuse it. Clients pass <code class="inline">Authorization: ApiKey <key></code> on every request.</p>diff --git a/landing/docs/install.html b/landing/docs/install.htmlindex a1c3bd8d1..8b00a28ed 100644--- a/landing/docs/install.html+++ b/landing/docs/install.html@@ -156,7 +156,10 @@ $ xerj --version</pre><pre class="code"># /etc/xerj/xerj.toml[server]rest_port = 8080+# Default is "127.0.0.1" (loopback only). Exposing the node while TLS is off+# needs the second line too, or startup refuses.bind_address = "0.0.0.0"+allow_insecure_network_bind = truedata_dir = "/var/lib/xerj"[auth]diff --git a/landing/docs/security.html b/landing/docs/security.htmlindex 2a81a3e92..0620853ae 100644--- a/landing/docs/security.html+++ b/landing/docs/security.html@@ -141,7 +141,8 @@ key_path = "/etc/xerj/certs/xerj.key"</pre><pre class="code">$ sudo systemctl reload xerj</pre><h2>Network</h2>- <p>Use <code class="inline">bind_address</code> to restrict the listener to a private interface. Never bind <code class="inline">0.0.0.0</code> without TLS and auth on in production. The <code class="inline">--insecure</code> flag is dev-only and refuses to run with a non-loopback bind.</p>+ <p><code class="inline">bind_address</code> defaults to <code class="inline">127.0.0.1</code>: a node you have not configured is reachable from its own host and nowhere else. Set it (or pass <code class="inline">--bind</code> / <code class="inline">XERJ_BIND_ADDRESS</code>) to expose the node.</p>+ <p>With <code class="inline">tls.enabled = false</code>, a non-loopback bind <strong>refuses to start</strong> — every listener would serve plain HTTP, putting the API key in every <code class="inline">Authorization</code> header on the wire. Either enable TLS, or declare the exposure with <code class="inline">server.allow_insecure_network_bind = true</code> when something in front of the node already terminates TLS. <code class="inline">--insecure</code> does not evade this: it clears <code class="inline">tls.enabled</code>, so it trips the same check.</p><p class="source-note">Source · engine/crates/common/src/config.rs · api/src/middleware/auth.rs</p>