From 3d5b252c174af87439c0ee0e45d5e8f0df566b6d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 19:20:52 +0000 Subject: [PATCH 1/3] Require an explicit opt-in for unauthenticated loopback An empty secret no longer starts a listener, including on loopback. Whitespace-only secrets are rejected by startup and by both bearer interceptors. allow_unauthenticated is the loopback-only development flag, and unknown auth-like keys are no longer ignored. Co-authored-by: RustFS --- crates/metadb-raft/src/network.rs | 2 +- crates/metadb-server/src/config.rs | 128 ++++++++++++++++-- crates/metadb-server/src/lib.rs | 83 ++++++++---- crates/metadb-server/src/metrics_http.rs | 22 ++- crates/metadb-server/src/stress.rs | 3 + .../metadb-server/tests/auth_fail_closed.rs | 94 +++++++------ crates/metadb-server/tests/backup_restore.rs | 3 + .../tests/control_plane_claim_tests.rs | 1 + .../tests/e2e_cluster_evolution_tests.rs | 3 + .../metadb-server/tests/grpc_regressions.rs | 2 + .../metadb-server/tests/integration_tests.rs | 3 + .../tests/join_existing_group.rs | 8 ++ crates/metadb-server/tests/prefix_load.rs | 1 + .../tests/rename_concurrency_regressions.rs | 1 + .../metadb-server/tests/round2_api_tests.rs | 1 + .../metadb-server/tests/round2_cli_tests.rs | 2 + .../tests/round2_mixed_shard_tests.rs | 1 + .../tests/round2_name_flush_tests.rs | 1 + .../tests/round2_namespace_tests.rs | 1 + .../tests/round2_quota_order_tests.rs | 1 + .../tests/round2_restart_routes_tests.rs | 2 + .../tests/scale_in_restart_tests.rs | 3 + .../tests/security_adversarial_regressions.rs | 53 ++------ .../tests/snapshot_status_tests.rs | 2 + docs/en/architecture.md | 4 +- docs/en/build-and-run.md | 2 +- docs/en/configuration.md | 13 +- docs/en/operations.md | 4 +- docs/en/testing.md | 7 +- docs/guides/en/deployment.md | 2 +- 30 files changed, 307 insertions(+), 146 deletions(-) diff --git a/crates/metadb-raft/src/network.rs b/crates/metadb-raft/src/network.rs index af6a1a3..c93a1d8 100644 --- a/crates/metadb-raft/src/network.rs +++ b/crates/metadb-raft/src/network.rs @@ -102,7 +102,7 @@ pub struct ChannelPool { impl ChannelPool { /// Configures authentication for all Raft clients sharing this pool. pub fn set_shared_secret(&self, secret: Option) { - *self.shared_secret.write().unwrap() = secret.filter(|s| !s.is_empty()); + *self.shared_secret.write().unwrap() = secret.filter(|s| !s.trim().is_empty()); } fn authenticate(&self, mut request: Request) -> Result, io::Error> { diff --git a/crates/metadb-server/src/config.rs b/crates/metadb-server/src/config.rs index 78140f9..7683acb 100644 --- a/crates/metadb-server/src/config.rs +++ b/crates/metadb-server/src/config.rs @@ -98,14 +98,52 @@ impl Default for StorageSection { /// Application-level bearer auth. This process does not terminate TLS. /// -/// An empty `shared_secret` is accepted only for loopback listeners. A wildcard or -/// any other non-loopback bind with an empty secret refuses to start. When the -/// secret is non-empty, gRPC and the metrics listener require the same bearer. +/// An empty `shared_secret` does not start a listener. Loopback development +/// without credentials requires `allow_unauthenticated = true`, and that flag +/// still refuses every non-loopback bind. A whitespace-only secret is rejected. +/// A non-empty secret requires the same bearer on gRPC and metrics. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct SecuritySection { - /// When non-empty, gRPC and metrics require `authorization: Bearer `. + /// When non-empty and not whitespace, gRPC and metrics require + /// `authorization: Bearer ` exactly, including any surrounding spaces + /// that are part of a secret which also contains other characters. pub shared_secret: String, + /// Explicit opt-in for unauthenticated loopback listeners. + /// + /// Default is `false`. Setting this does not allow `0.0.0.0`, `::`, or any + /// other non-loopback address. It cannot be combined with a usable secret. + pub allow_unauthenticated: bool, +} + +impl SecuritySection { + /// Rejects whitespace-only secrets, a missing secret without the loopback opt-in, + /// and a usable secret combined with that opt-in. + pub fn validate_for_startup(&self) -> Result<()> { + if !self.shared_secret.is_empty() && self.shared_secret.trim().is_empty() { + return Err(MetaDbError::CodecError( + "refusing to serve: [security].shared_secret is whitespace-only. It is not a credential and it is not unauthenticated mode. Set a secret that contains a non-whitespace character, or leave the secret empty and set allow_unauthenticated = true for loopback development".to_string(), + )); + } + if self.shared_secret.is_empty() { + if self.allow_unauthenticated { + return Ok(()); + } + return Err(MetaDbError::CodecError( + "refusing to serve without [security].shared_secret. Loopback is not an implicit exception. Set a non-empty shared_secret, or set allow_unauthenticated = true and bind only loopback addresses".to_string(), + )); + } + if self.allow_unauthenticated { + return Err(MetaDbError::CodecError( + "refusing to serve: [security].shared_secret and allow_unauthenticated are both set. Remove one of them".to_string(), + )); + } + Ok(()) + } + + fn requires_bearer(&self) -> bool { + !self.shared_secret.trim().is_empty() + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -188,12 +226,13 @@ impl ServerTomlConfig { }) } - /// Refuses to start when a listener is not loopback and no secret is configured. + /// Refuses to start when authentication is missing, whitespace-only, or ambiguous, + /// and when an explicit unauthenticated opt-in is bound beyond loopback. /// /// Call this on the configured addresses and again on the address that will /// actually be bound (a restarted process may reuse a saved advertise address). pub fn reject_unauthenticated_bind(&self, addr: &str) -> Result<()> { - reject_unauthenticated_bind(addr, &self.security.shared_secret) + reject_unauthenticated_bind(addr, &self.security) } } @@ -213,12 +252,13 @@ fn is_loopback_bind(addr: &str) -> bool { } } -fn reject_unauthenticated_bind(addr: &str, secret: &str) -> Result<()> { - if !secret.trim().is_empty() || is_loopback_bind(addr) { +fn reject_unauthenticated_bind(addr: &str, security: &SecuritySection) -> Result<()> { + security.validate_for_startup()?; + if security.requires_bearer() || is_loopback_bind(addr) { return Ok(()); } Err(MetaDbError::CodecError(format!( - "refusing to serve unauthenticated listener {addr}; a wildcard or non-loopback bind requires a non-empty [security].shared_secret. Empty, missing, and misspelled secrets fail closed. This process does not terminate TLS" + "refusing to serve unauthenticated listener {addr}; allow_unauthenticated is loopback-only. A wildcard or other non-loopback bind requires a non-empty [security].shared_secret. This process does not terminate TLS" ))) } @@ -261,6 +301,8 @@ fn is_secret_key(key: &str) -> bool { "token", "credential", "auth", + "anonymous", + "insecure", ] .iter() .any(|needle| key.contains(needle)) @@ -274,7 +316,7 @@ fn security_key_error(key: &str) -> MetaDbError { )) } else { MetaDbError::CodecError(format!( - "refusing to start: unrecognized security key `{key}`. A missing or misspelled shared_secret must not leave listeners open. The only accepted security key is [security].shared_secret" + "refusing to start: unrecognized security key `{key}`. A missing or misspelled shared_secret must not leave listeners open. The only accepted security keys are [security].shared_secret and [security].allow_unauthenticated" )) } } @@ -288,11 +330,11 @@ fn reject_unsupported_security_keys(value: &toml::Value) -> Result<()> { if let Some(security) = root.get("security") { let Some(table) = security.as_table() else { return Err(MetaDbError::CodecError( - "refusing to start: [security] must be a table. The only accepted security key is [security].shared_secret".to_string(), + "refusing to start: [security] must be a table. The only accepted security keys are shared_secret and allow_unauthenticated".to_string(), )); }; for (key, child) in table { - if key != "shared_secret" { + if key != "shared_secret" && key != "allow_unauthenticated" { return Err(security_key_error(key)); } // The secret value itself must not smuggle a nested TLS or secret table. @@ -379,6 +421,13 @@ mod tests { #[test] fn loopback_binds_are_explicit_and_wildcards_are_not() { + let mut opted_in = ServerTomlConfig::default(); + opted_in.security.allow_unauthenticated = true; + let implicit = ServerTomlConfig::default(); + let mut whitespace = ServerTomlConfig::default(); + whitespace.security.shared_secret = " ".into(); + let mut configured = ServerTomlConfig::default(); + configured.security.shared_secret = "secret".into(); for addr in [ "127.0.0.1:7800", "127.0.0.1:0", @@ -386,7 +435,19 @@ mod tests { "[::1]:7800", ] { assert!(is_loopback_bind(addr), "{addr}"); - assert!(reject_unauthenticated_bind(addr, "").is_ok(), "{addr}"); + assert!(opted_in.reject_unauthenticated_bind(addr).is_ok(), "{addr}"); + let implicit_err = implicit.reject_unauthenticated_bind(addr).unwrap_err(); + assert!( + implicit_err + .to_string() + .contains("not an implicit exception"), + "{addr}: {implicit_err}" + ); + let whitespace_err = whitespace.reject_unauthenticated_bind(addr).unwrap_err(); + assert!( + whitespace_err.to_string().contains("whitespace-only"), + "{addr}: {whitespace_err}" + ); } for addr in [ "0.0.0.0:7800", @@ -395,10 +456,17 @@ mod tests { "db.internal:7800", ] { assert!(!is_loopback_bind(addr), "{addr}"); - let err = reject_unauthenticated_bind(addr, " ").unwrap_err(); + let err = opted_in.reject_unauthenticated_bind(addr).unwrap_err(); assert!(err.to_string().contains("refusing to serve"), "{err}"); } - assert!(reject_unauthenticated_bind("0.0.0.0:7800", "secret").is_ok()); + assert!(configured + .reject_unauthenticated_bind("0.0.0.0:7800") + .is_ok()); + configured.security.allow_unauthenticated = true; + let both = configured + .reject_unauthenticated_bind("127.0.0.1:7800") + .unwrap_err(); + assert!(both.to_string().contains("both set"), "{both}"); } #[test] @@ -478,6 +546,36 @@ mod tests { "{listeners_err}" ); + let anonymous = ServerTomlConfig::from_toml_str( + r#" + [security] + anonymous = true + "#, + ); + assert!( + anonymous.unwrap_err().to_string().contains("anonymous"), + "an unknown auth field inside [security] must not be ignored" + ); + let insecure = ServerTomlConfig::from_toml_str( + r#" + [node] + insecure = true + "#, + ); + assert!( + insecure.unwrap_err().to_string().contains("insecure"), + "an insecure flag outside [security] must not be ignored" + ); + let opted_in = ServerTomlConfig::from_toml_str( + r#" + [security] + allow_unauthenticated = true + "#, + ) + .unwrap(); + assert!(opted_in.security.allow_unauthenticated); + assert!(opted_in.security.shared_secret.is_empty()); + let cfg = ServerTomlConfig::from_toml_str( r#" [node] diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index 34530cf..bd2fbad 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -27,9 +27,11 @@ use tonic::service::Interceptor; use tonic::transport::{Endpoint, Server}; use tonic::{Request, Status}; -/// Server interceptor for metadata, transaction, and control-plane RPCs. -/// An empty secret allows the call (loopback deployments without auth). -/// A non-empty secret requires `authorization: Bearer ` on the incoming request. +/// Server interceptor for metadata, transaction, control-plane, and Raft RPCs. +/// +/// An empty secret allows the call. `open_and_serve` only reaches that state when +/// `allow_unauthenticated` is set. A whitespace-only secret rejects every call. +/// Any other secret requires `authorization: Bearer ` exactly. #[derive(Clone)] pub struct BearerAuth { secret: std::sync::Arc, @@ -58,28 +60,49 @@ pub(crate) fn bearer_header_matches(presented: &str, secret: &str) -> bool { diff == 0 } +pub(crate) enum SecretMaterial { + Absent, + WhitespaceOnly, + Configured, +} + +pub(crate) fn classify_secret(secret: &str) -> SecretMaterial { + if secret.is_empty() { + SecretMaterial::Absent + } else if secret.trim().is_empty() { + SecretMaterial::WhitespaceOnly + } else { + SecretMaterial::Configured + } +} + impl Interceptor for BearerAuth { fn call(&mut self, request: Request<()>) -> std::result::Result, Status> { - if self.secret.is_empty() { - return Ok(request); - } - let presented = request - .metadata() - .get("authorization") - .and_then(|value| value.to_str().ok()) - .unwrap_or(""); - if bearer_header_matches(presented, &self.secret) { - Ok(request) - } else { - Err(Status::unauthenticated( - "missing or invalid authorization bearer token", - )) + match classify_secret(&self.secret) { + SecretMaterial::Absent => Ok(request), + SecretMaterial::WhitespaceOnly => Err(Status::unauthenticated( + "whitespace-only shared secret is not accepted", + )), + SecretMaterial::Configured => { + let presented = request + .metadata() + .get("authorization") + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if bearer_header_matches(presented, &self.secret) { + Ok(request) + } else { + Err(Status::unauthenticated( + "missing or invalid authorization bearer token", + )) + } + } } } } /// Client interceptor. Attaches `authorization: Bearer ` to outgoing RPCs. -/// An empty secret leaves the request unchanged. +/// An empty secret leaves the request unchanged. A whitespace-only secret is rejected. #[derive(Clone)] pub struct BearerAuthClient { secret: std::sync::Arc, @@ -95,8 +118,14 @@ impl BearerAuthClient { impl Interceptor for BearerAuthClient { fn call(&mut self, mut request: Request<()>) -> std::result::Result, Status> { - if self.secret.is_empty() { - return Ok(request); + match classify_secret(&self.secret) { + SecretMaterial::Absent => return Ok(request), + SecretMaterial::WhitespaceOnly => { + return Err(Status::unauthenticated( + "whitespace-only shared secret is not a credential", + )); + } + SecretMaterial::Configured => {} } let mut token = String::from("Bearer "); token.push_str(&self.secret); @@ -660,10 +689,8 @@ impl PersistentMetaDbCluster { if shared_secret.is_empty() { tracing::warn!( listen = %bound_addr, - "gRPC and metrics listeners have no authentication and this process does not terminate TLS. \ - An empty shared_secret is accepted only for loopback binds. \ - A wildcard or other non-loopback address refuses to serve. \ - RaftTransport on this listener requires the same bearer when the secret is set." + "allow_unauthenticated is set. Loopback gRPC and metrics listeners have no authentication. \ + This process does not terminate TLS. Non-loopback binds are still refused." ); } let grpc_handle = @@ -1472,4 +1499,12 @@ mod auth_tests { let outgoing = client.call(Request::new(())).unwrap(); assert!(authorization(&outgoing).is_none()); } + + #[test] + fn whitespace_secret_is_rejected_by_client_and_server() { + let mut server = BearerAuth::new(" "); + assert!(server.call(Request::new(())).is_err()); + let mut client = BearerAuthClient::new(" \t "); + assert!(client.call(Request::new(())).is_err()); + } } diff --git a/crates/metadb-server/src/metrics_http.rs b/crates/metadb-server/src/metrics_http.rs index b17fd0c..defbf18 100644 --- a/crates/metadb-server/src/metrics_http.rs +++ b/crates/metadb-server/src/metrics_http.rs @@ -14,8 +14,10 @@ use tokio::sync::watch; use tokio::task::JoinSet; use crate::bearer_header_matches; +use crate::classify_secret; use crate::render_prometheus_metrics; use crate::PersistentMetaDbCluster; +use crate::SecretMaterial; const METRICS_MAX_CONNECTIONS: usize = 64; const METRICS_MAX_HEADER_BYTES: usize = 8192; @@ -99,15 +101,21 @@ fn metrics_decision( cluster: &Weak, shared_secret: &str, ) -> (StatusCode, String, bool) { - if !shared_secret.is_empty() { - let presented = request - .headers() - .get(hyper::header::AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .unwrap_or(""); - if !bearer_header_matches(presented, shared_secret) { + match classify_secret(shared_secret) { + SecretMaterial::Absent => {} + SecretMaterial::WhitespaceOnly => { return (StatusCode::UNAUTHORIZED, "unauthorized\n".to_owned(), false); } + SecretMaterial::Configured => { + let presented = request + .headers() + .get(hyper::header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !bearer_header_matches(presented, shared_secret) { + return (StatusCode::UNAUTHORIZED, "unauthorized\n".to_owned(), false); + } + } } if request.method() != Method::GET { return ( diff --git a/crates/metadb-server/src/stress.rs b/crates/metadb-server/src/stress.rs index 3dc4c76..f93bdff 100644 --- a/crates/metadb-server/src/stress.rs +++ b/crates/metadb-server/src/stress.rs @@ -136,6 +136,9 @@ mvcc_retention_ms = 5000 [sharding] bootstrap_table_shards = true shard_split_threshold_bytes = {shard_split_threshold_bytes} + +[security] +allow_unauthenticated = true "#, data_dir.display() ); diff --git a/crates/metadb-server/tests/auth_fail_closed.rs b/crates/metadb-server/tests/auth_fail_closed.rs index 6be4702..22592f9 100644 --- a/crates/metadb-server/tests/auth_fail_closed.rs +++ b/crates/metadb-server/tests/auth_fail_closed.rs @@ -3,13 +3,10 @@ //! These tests only send a missing or wrong credential and expect rejection, or they //! expect startup to refuse a listener. They do not attempt to bypass authentication. //! -//! Two cases lock current behavior that is still a gap: -//! -//! - An empty `shared_secret` on `127.0.0.1` serves metadata, transactions, the -//! control plane, and metrics with no credentials. A post-merge run that used -//! loopback and an empty secret did not prove fail-closed authentication. -//! - Unknown TOML keys that do not look like a secret or TLS setting are ignored. -//! A misspelled storage or join key still starts the process. +//! An empty secret does not listen, including on loopback, unless +//! `allow_unauthenticated` is set. A whitespace-only secret never listens. +//! Unknown auth-like keys are rejected. Unknown keys that are not auth or TLS +//! settings are still ignored. use std::time::Duration; @@ -272,18 +269,42 @@ fn with_authorization( request } -/// Loopback with an empty secret is the local-development path. It is not fail-closed. -/// -/// A run that binds `127.0.0.1` and leaves `shared_secret` empty, including the -/// post-merge Mac mini run, accepts callers that send no credentials. +/// Loopback is not an implicit exception. An empty secret must not listen. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn empty_secret_on_loopback_serves_without_credentials() { +async fn empty_secret_on_loopback_does_not_listen() { + let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = probe.local_addr().unwrap().port(); + drop(probe); + let mut cfg = ServerTomlConfig::default(); + cfg.node.data_dir = std::env::temp_dir().join(format!("metadb-empty-loopback-{port}")); + cfg.node.grpc_listen_addr = format!("127.0.0.1:{port}"); + cfg.node.metrics_listen_addr = Some(format!("127.0.0.1:{port}")); + cfg.security.shared_secret.clear(); + cfg.security.allow_unauthenticated = false; + let err = match PersistentMetaDbCluster::open_and_serve(cfg).await { + Ok((cluster, _)) => { + let _ = cluster.shutdown().await; + panic!("empty secret on loopback must not start"); + } + Err(err) => err, + }; + assert!( + err.to_string().contains("not an implicit exception"), + "{err}" + ); + expect_closed(&format!("127.0.0.1:{port}")).await; +} + +/// The explicit opt-in still serves loopback without credentials. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn explicit_unauthenticated_loopback_serves_without_credentials() { let dir = tempfile::tempdir().unwrap(); let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); cfg.node.metrics_listen_addr = Some("127.0.0.1:0".into()); cfg.security.shared_secret.clear(); + cfg.security.allow_unauthenticated = true; let (cluster, grpc_addr) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); assert!( grpc_addr.starts_with("127.0.0.1:"), @@ -528,40 +549,26 @@ async fn configured_secret_rejects_basic_auth_without_applying_the_write() { assert!(bearer_metrics.1.contains("metadb_shards_total")); } -/// Whitespace is not an empty secret once a listener is up. Loopback still starts, -/// and a missing bearer is rejected instead of being treated as anonymous access. +/// A whitespace-only secret is not a credential and does not open loopback. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn whitespace_secret_on_loopback_rejects_anonymous_calls() { - let dir = tempfile::tempdir().unwrap(); +async fn whitespace_secret_on_loopback_does_not_listen() { + let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = probe.local_addr().unwrap().port(); + drop(probe); let mut cfg = ServerTomlConfig::default(); - cfg.node.data_dir = dir.path().to_path_buf(); - cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); - cfg.node.metrics_listen_addr = Some("127.0.0.1:0".into()); + cfg.node.grpc_listen_addr = format!("127.0.0.1:{port}"); + cfg.node.metrics_listen_addr = Some(format!("127.0.0.1:{port}")); cfg.security.shared_secret = " ".into(); - let (cluster, grpc_addr) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); - let metrics_dial = loopback_dial(cluster.metrics_addr().expect("metrics listener")); - let channel = Endpoint::from_shared(format!("http://{grpc_addr}")) - .unwrap() - .connect() - .await - .unwrap(); - let mut status = ControlPlaneServiceClient::new(channel); - let anonymous = status.get_routes(GetRoutesRequest { cell_id: 0 }).await; - let mut exact = tonic::Request::new(GetRoutesRequest { cell_id: 0 }); - exact - .metadata_mut() - .insert("authorization", "Bearer ".parse().unwrap()); - let accepted = status.get_routes(exact).await; - let metrics = http_exchange(&metrics_dial, None, "/metrics").await; - cluster.shutdown().await.unwrap(); - - assert_eq!(anonymous.unwrap_err().code(), Code::Unauthenticated); - assert!(accepted - .expect("exact whitespace bearer") - .into_inner() - .error - .is_none()); - assert_rejected_http(metrics.0, &metrics.1); + cfg.security.allow_unauthenticated = true; + let err = match PersistentMetaDbCluster::open_and_serve(cfg).await { + Ok((cluster, _)) => { + let _ = cluster.shutdown().await; + panic!("whitespace secret must not start, even with the loopback opt-in"); + } + Err(err) => err, + }; + assert!(err.to_string().contains("whitespace-only"), "{err}"); + expect_closed(&format!("127.0.0.1:{port}")).await; } /// Unknown keys that do not name a secret or TLS setting are still ignored. @@ -588,6 +595,7 @@ async fn unknown_toml_keys_are_ignored_and_loopback_still_serves() { [security] shared_secret = "" + allow_unauthenticated = true "#, ) .expect("non-secret unknown keys are ignored and must not fail the parse"); diff --git a/crates/metadb-server/tests/backup_restore.rs b/crates/metadb-server/tests/backup_restore.rs index 8b1bd54..ae761b5 100644 --- a/crates/metadb-server/tests/backup_restore.rs +++ b/crates/metadb-server/tests/backup_restore.rs @@ -26,6 +26,9 @@ grpc_listen_addr = "127.0.0.1:0" [sharding] bootstrap_table_shards = true shard_split_threshold_bytes = 4294967296 + +[security] +allow_unauthenticated = true "#, dir.display() ); diff --git a/crates/metadb-server/tests/control_plane_claim_tests.rs b/crates/metadb-server/tests/control_plane_claim_tests.rs index 5d107bf..a3ea62a 100644 --- a/crates/metadb-server/tests/control_plane_claim_tests.rs +++ b/crates/metadb-server/tests/control_plane_claim_tests.rs @@ -42,6 +42,7 @@ async fn control_plane_does_not_pretend_missing_topology_ops_succeeded() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, _) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let svc = MetaDbGrpcService::new( cluster.global_manager().clone(), diff --git a/crates/metadb-server/tests/e2e_cluster_evolution_tests.rs b/crates/metadb-server/tests/e2e_cluster_evolution_tests.rs index 903e064..f3c238d 100644 --- a/crates/metadb-server/tests/e2e_cluster_evolution_tests.rs +++ b/crates/metadb-server/tests/e2e_cluster_evolution_tests.rs @@ -51,6 +51,9 @@ locality_tombstone_ratio = 0.50 [sharding] bootstrap_table_shards = true shard_split_threshold_bytes = 2048 + +[security] +allow_unauthenticated = true "#, dir.path().display() ); diff --git a/crates/metadb-server/tests/grpc_regressions.rs b/crates/metadb-server/tests/grpc_regressions.rs index 81ef4bb..b634be6 100644 --- a/crates/metadb-server/tests/grpc_regressions.rs +++ b/crates/metadb-server/tests/grpc_regressions.rs @@ -12,6 +12,7 @@ fn config(dir: &std::path::Path) -> ServerTomlConfig { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; cfg } @@ -123,6 +124,7 @@ async fn configured_secret_protects_raft_transport() { let dir = tempfile::tempdir().unwrap(); let mut cfg = config(dir.path()); cfg.security.shared_secret = "test-secret".into(); + cfg.security.allow_unauthenticated = false; let (cluster, addr) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let channel = tonic::transport::Endpoint::from_shared(format!("http://{addr}")) .unwrap() diff --git a/crates/metadb-server/tests/integration_tests.rs b/crates/metadb-server/tests/integration_tests.rs index ffb4ff7..4054dd6 100644 --- a/crates/metadb-server/tests/integration_tests.rs +++ b/crates/metadb-server/tests/integration_tests.rs @@ -408,6 +408,9 @@ grpc_listen_addr = "127.0.0.1:0" [sharding] bootstrap_table_shards = true shard_split_threshold_bytes = 4294967296 + +[security] +allow_unauthenticated = true "#, dir.display() ); diff --git a/crates/metadb-server/tests/join_existing_group.rs b/crates/metadb-server/tests/join_existing_group.rs index 5e17b5b..2ab2296 100644 --- a/crates/metadb-server/tests/join_existing_group.rs +++ b/crates/metadb-server/tests/join_existing_group.rs @@ -40,6 +40,9 @@ shard_split_threshold_bytes = 4294967296 [cluster] join = "{join}" + +[security] +allow_unauthenticated = true "#, dir.display() ); @@ -462,6 +465,7 @@ async fn join_sends_the_shared_secret() { let dir = tempdir().unwrap(); let mut cfg1 = fast_config(&dir.path().join("n1"), 1, ""); cfg1.security.shared_secret = "join-secret".to_string(); + cfg1.security.allow_unauthenticated = false; let (node1, addr1) = PersistentMetaDbCluster::open_and_serve(cfg1).await.unwrap(); node1 .tx_router() @@ -471,6 +475,7 @@ async fn join_sends_the_shared_secret() { assert!(create_named(&node1, "before_join.dat", 100, 500).await); let mut cfg2 = fast_config(&dir.path().join("n2"), 2, &addr1); cfg2.security.shared_secret = "join-secret".to_string(); + cfg2.security.allow_unauthenticated = false; let (node2, _) = PersistentMetaDbCluster::open_and_serve(cfg2).await.unwrap(); wait_applied(&node2, "before_join.dat").await; assert_eq!(voter_set(&node1), BTreeSet::from([1, 2])); @@ -564,6 +569,9 @@ shard_split_threshold_bytes = 4294967296 [cluster] join = "{join}" + +[security] +allow_unauthenticated = true "#, data_dir.display() ) diff --git a/crates/metadb-server/tests/prefix_load.rs b/crates/metadb-server/tests/prefix_load.rs index 716db9c..882b12f 100644 --- a/crates/metadb-server/tests/prefix_load.rs +++ b/crates/metadb-server/tests/prefix_load.rs @@ -696,6 +696,7 @@ async fn ci_prefix_load() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, addr) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let endpoints = vec![format!("http://{addr}")]; let result = run_load(&endpoints, "", &profile).await; diff --git a/crates/metadb-server/tests/rename_concurrency_regressions.rs b/crates/metadb-server/tests/rename_concurrency_regressions.rs index 0b71073..095eaac 100644 --- a/crates/metadb-server/tests/rename_concurrency_regressions.rs +++ b/crates/metadb-server/tests/rename_concurrency_regressions.rs @@ -10,6 +10,7 @@ async fn opposing_directory_renames_remain_reachable_with_eight_clients() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, _) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let tx = cluster.tx_router().clone(); tx.mkdir(ROOT_INODE_ID, "A", 10, 5, 0o755).await.unwrap(); diff --git a/crates/metadb-server/tests/round2_api_tests.rs b/crates/metadb-server/tests/round2_api_tests.rs index 3b4d874..8671dcf 100644 --- a/crates/metadb-server/tests/round2_api_tests.rs +++ b/crates/metadb-server/tests/round2_api_tests.rs @@ -21,6 +21,7 @@ async fn start( let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, addr) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let client = MetadataServiceClient::connect(format!("http://{addr}")) .await diff --git a/crates/metadb-server/tests/round2_cli_tests.rs b/crates/metadb-server/tests/round2_cli_tests.rs index b3117c3..2677436 100644 --- a/crates/metadb-server/tests/round2_cli_tests.rs +++ b/crates/metadb-server/tests/round2_cli_tests.rs @@ -6,6 +6,7 @@ async fn start(dir: &std::path::Path) -> (Arc, String) let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap() } @@ -186,6 +187,7 @@ async fn idle_metrics_connection_must_not_block_other_scrapes() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().join("data"); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; cfg.node.metrics_listen_addr = Some("127.0.0.1:0".into()); std::fs::write(&config_path, toml::to_string(&cfg).unwrap()).unwrap(); let mut daemon = tokio::process::Command::new(env!("CARGO_BIN_EXE_metadbd")) diff --git a/crates/metadb-server/tests/round2_mixed_shard_tests.rs b/crates/metadb-server/tests/round2_mixed_shard_tests.rs index 4704cff..341fab7 100644 --- a/crates/metadb-server/tests/round2_mixed_shard_tests.rs +++ b/crates/metadb-server/tests/round2_mixed_shard_tests.rs @@ -6,6 +6,7 @@ async fn all_tables_single_shard_configuration_must_support_split() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; cfg.sharding.bootstrap_table_shards = false; let (cluster, _) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let tx = cluster.tx_router(); diff --git a/crates/metadb-server/tests/round2_name_flush_tests.rs b/crates/metadb-server/tests/round2_name_flush_tests.rs index e92e984..400045f 100644 --- a/crates/metadb-server/tests/round2_name_flush_tests.rs +++ b/crates/metadb-server/tests/round2_name_flush_tests.rs @@ -6,6 +6,7 @@ async fn accepted_user_name_must_be_representable_in_sstable() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, _) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let created = cluster .create_file_auto_id(1, &"a".repeat(70_000), 7, 0o644, 1) diff --git a/crates/metadb-server/tests/round2_namespace_tests.rs b/crates/metadb-server/tests/round2_namespace_tests.rs index b261197..b93b4ff 100644 --- a/crates/metadb-server/tests/round2_namespace_tests.rs +++ b/crates/metadb-server/tests/round2_namespace_tests.rs @@ -4,6 +4,7 @@ async fn start(dir: &std::path::Path) -> std::sync::Arc let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; PersistentMetaDbCluster::open_and_serve(cfg) .await .unwrap() diff --git a/crates/metadb-server/tests/round2_quota_order_tests.rs b/crates/metadb-server/tests/round2_quota_order_tests.rs index 0d61d0c..cc56dff 100644 --- a/crates/metadb-server/tests/round2_quota_order_tests.rs +++ b/crates/metadb-server/tests/round2_quota_order_tests.rs @@ -9,6 +9,7 @@ async fn cross_origin_quota_deltas_must_conserve_totals_under_reordered_delivery let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (cluster, _) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); let (_, quota_group, _) = cluster.cell_manager().lookup_local_handle(2).unwrap(); // Valid causal history: create on origin 1, rename to origin 4, unlink there. diff --git a/crates/metadb-server/tests/round2_restart_routes_tests.rs b/crates/metadb-server/tests/round2_restart_routes_tests.rs index bb6ce72..289879d 100644 --- a/crates/metadb-server/tests/round2_restart_routes_tests.rs +++ b/crates/metadb-server/tests/round2_restart_routes_tests.rs @@ -7,6 +7,7 @@ async fn advertised_local_peer_address_must_follow_listener_after_restart() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (first, old_address) = PersistentMetaDbCluster::open_and_serve(cfg.clone()) .await .unwrap(); @@ -49,6 +50,7 @@ async fn reopening_another_nodes_directory_is_rejected() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; let (first, _) = PersistentMetaDbCluster::open_and_serve(cfg.clone()) .await .unwrap(); diff --git a/crates/metadb-server/tests/scale_in_restart_tests.rs b/crates/metadb-server/tests/scale_in_restart_tests.rs index dd91ab2..84d59b1 100644 --- a/crates/metadb-server/tests/scale_in_restart_tests.rs +++ b/crates/metadb-server/tests/scale_in_restart_tests.rs @@ -41,6 +41,9 @@ shard_split_threshold_bytes = 4294967296 [cluster] join = "{join}" + +[security] +allow_unauthenticated = true "#, dir.display() ); diff --git a/crates/metadb-server/tests/security_adversarial_regressions.rs b/crates/metadb-server/tests/security_adversarial_regressions.rs index a60469c..5e91610 100644 --- a/crates/metadb-server/tests/security_adversarial_regressions.rs +++ b/crates/metadb-server/tests/security_adversarial_regressions.rs @@ -5,12 +5,10 @@ //! of that gap, not a first-ship security pass. use metadb_core::ROOT_INODE_ID; -use metadb_proto::control_plane_service_client::ControlPlaneServiceClient; use metadb_proto::metadata_service_client::MetadataServiceClient; -use metadb_proto::{CreateFileRequest, GetRoutesRequest, LookupRequest}; +use metadb_proto::{CreateFileRequest, LookupRequest}; use metadb_server::{BearerAuthClient, PersistentMetaDbCluster, ServerTomlConfig}; use tonic::transport::Endpoint; -use tonic::Code; fn with_data_dir(mut cfg: ServerTomlConfig, dir: &std::path::Path) -> ServerTomlConfig { cfg.node.data_dir = dir.to_path_buf(); @@ -61,49 +59,22 @@ async fn persisted_non_loopback_advertise_without_secret_fails_closed() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn loopback_whitespace_secret_is_not_treated_as_empty() { - // `reject_unauthenticated_bind` trims the secret, so a whitespace-only value - // still lets a loopback listener start. `BearerAuth` does not trim: it - // compares the secret as stored. A missing bearer is rejected, a different - // whitespace bearer is rejected, and only the literal whitespace bearer is - // accepted. This is a consistency gap. A green result is not a first-ship pass. +async fn loopback_whitespace_secret_does_not_start() { + // A whitespace-only secret used to start on loopback and accept only the + // literal whitespace bearer. Startup now refuses that value. let dir = tempfile::tempdir().unwrap(); let mut cfg = ServerTomlConfig::default(); cfg = with_data_dir(cfg, dir.path()); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); cfg.security.shared_secret = " ".into(); - let (cluster, grpc_addr) = PersistentMetaDbCluster::open_and_serve(cfg) - .await - .expect("loopback plus a whitespace secret still starts"); - let channel = Endpoint::from_shared(format!("http://{grpc_addr}")) - .unwrap() - .connect() - .await - .unwrap(); - let missing = ControlPlaneServiceClient::new(channel.clone()) - .get_routes(GetRoutesRequest { cell_id: 0 }) - .await; - let mut other = - ControlPlaneServiceClient::with_interceptor(channel.clone(), BearerAuthClient::new(" ")); - let other = other.get_routes(GetRoutesRequest { cell_id: 0 }).await; - let mut literal = - ControlPlaneServiceClient::with_interceptor(channel, BearerAuthClient::new(" ")); - let accepted = literal.get_routes(GetRoutesRequest { cell_id: 0 }).await; - cluster.shutdown().await.unwrap(); - assert_eq!( - missing.unwrap_err().code(), - Code::Unauthenticated, - "a missing bearer must be rejected when the stored secret is whitespace" - ); - assert_eq!( - other.unwrap_err().code(), - Code::Unauthenticated, - "a different whitespace bearer must be rejected" - ); - assert!( - accepted.is_ok(), - "only the literal whitespace bearer should authenticate: {accepted:?}" - ); + let err = match PersistentMetaDbCluster::open_and_serve(cfg).await { + Ok((cluster, _)) => { + let _ = cluster.shutdown().await; + panic!("whitespace secret must not start"); + } + Err(err) => err, + }; + assert!(err.to_string().contains("whitespace-only"), "{err}"); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/metadb-server/tests/snapshot_status_tests.rs b/crates/metadb-server/tests/snapshot_status_tests.rs index f6bacb0..4182a6f 100644 --- a/crates/metadb-server/tests/snapshot_status_tests.rs +++ b/crates/metadb-server/tests/snapshot_status_tests.rs @@ -12,6 +12,7 @@ async fn unrecoverable_snapshot_is_not_reported_as_a_live_voter() { let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; cfg.sharding.bootstrap_table_shards = false; let (cluster, _address) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); cluster @@ -68,6 +69,7 @@ async fn routes_for_live_status_detects_missing_snapshot_without_prior_get_curre let mut cfg = ServerTomlConfig::default(); cfg.node.data_dir = dir.path().to_path_buf(); cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.security.allow_unauthenticated = true; cfg.sharding.bootstrap_table_shards = false; let (cluster, _address) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); cluster diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 06d8495..de69b60 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -9,13 +9,13 @@ This page follows the code in `crates/`. It does not describe a multi-process Ce `PersistentMetaDbCluster::open_and_serve` (`crates/metadb-server/src/lib.rs`): 1. Rejects any `node.role` other than `all-in-one`. -2. Refuses a wildcard or other non-loopback `grpc_listen_addr` or `metrics_listen_addr` when `shared_secret` is empty. Then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port). +2. Refuses to listen when `shared_secret` is empty or whitespace-only, unless `allow_unauthenticated` is set. That flag still refuses a wildcard or other non-loopback `grpc_listen_addr` or `metrics_listen_addr`. Then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port). 3. Opens `DurableIdAllocator` at `/global_allocator`. 4. Opens `ShardGroupHost` at `/be`. 5. Opens or bootstraps `DurableCellManager` at `/cell_`. 6. Registers that one cell on `DurableGlobalManager` for the key range `[0x01, 0x04)`. 7. Ensures root directory inode `1` (`ROOT_INODE_ID`) has an attribute record. -8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A non-empty secret rejects a missing or wrong bearer. An empty secret is accepted only for loopback binds. This process does not terminate TLS. +8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A usable secret rejects a missing or wrong bearer. An empty secret listens only when `allow_unauthenticated` is set, and only on loopback. This process does not terminate TLS. 9. Spawns a maintenance task on a 250 ms interval. `metadbd` is a thin wrapper: it loads TOML, applies CLI overrides, calls `open_and_serve`, optionally calls `RegisterNode` on `--cell-manager`, and on Ctrl-C calls `shutdown`. Metrics, when configured, are served inside `open_and_serve`. diff --git a/docs/en/build-and-run.md b/docs/en/build-and-run.md index 8b5b580..5e5a44a 100644 --- a/docs/en/build-and-run.md +++ b/docs/en/build-and-run.md @@ -64,7 +64,7 @@ cargo run -p metadb-server --bin metadbd -- --config ./standalone.toml Logs use `tracing-subscriber`'s `EnvFilter`. The default filter is `info`. Override it with the standard `RUST_LOG` variable, for example `RUST_LOG=debug`. -On startup with an empty `security.shared_secret`, the process logs a warning that loopback gRPC has no authentication. The default bind is `127.0.0.1`. A wildcard or other non-loopback address with an empty, missing, or misspelled secret refuses to listen. A non-empty `[security].shared_secret` requires the same bearer on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. The process does not terminate TLS. A TLS or certificate key in the config fails startup instead of serving plaintext. Keep the listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. +An empty `security.shared_secret` does not start the process. The default bind is `127.0.0.1`, and loopback is not an implicit exception. Local development without credentials sets `allow_unauthenticated = true` and keeps every listener on loopback. A wildcard or other non-loopback address still refuses to listen. A whitespace-only secret is rejected. A non-empty `[security].shared_secret` requires the same bearer on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the config fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. Ctrl-C flushes shard state and stops the OpenRaft groups (`cluster.shutdown()`). diff --git a/docs/en/configuration.md b/docs/en/configuration.md index a3c92b4..d5472a6 100644 --- a/docs/en/configuration.md +++ b/docs/en/configuration.md @@ -2,7 +2,7 @@ [Overview](./README.md) · [Français](../fr/configuration.md) · [Deutsch](../de/configuration.md) · [日本語](../ja/configuration.md) · [简体中文](../zh/configuration.md) -`metadbd --config` and `ServerTomlConfig::from_toml_file` / `from_toml_str` read TOML (`crates/metadb-server/src/config.rs`). Unknown keys that do not name a secret or TLS setting are ignored. A misspelled `shared_secret`, a token or password key, or any TLS or certificate key is rejected and startup does not proceed, including those keys nested in tables or arrays. `[security].shared_secret` is accepted only as a direct key of the root `[security]` table. Every known section is optional. Omitted fields take the defaults below. +`metadbd --config` and `ServerTomlConfig::from_toml_file` / `from_toml_str` read TOML (`crates/metadb-server/src/config.rs`). Unknown keys that do not name a secret, authentication, or TLS setting are ignored. A misspelled `shared_secret`, a token, password, anonymous, or insecure key, or any TLS or certificate key is rejected and startup does not proceed, including those keys nested in tables or arrays. The only accepted keys directly under the root `[security]` table are `shared_secret` and `allow_unauthenticated`. Every known section is optional. Omitted fields take the defaults below. ## Defaults @@ -24,7 +24,8 @@ | `storage.locality_tombstone_ratio` | `0.50` | Yes. Multiplied by 1000, clamped to 1..=1000, stored as `tombstone_min_ratio_permille` | | `sharding.bootstrap_table_shards` | `true` | Yes. `true` creates shards 1, 2, and 3. `false` creates shard 1 over `[0x01, 0x04)` | | `sharding.shard_split_threshold_bytes` | `4294967296` (4 GiB) | Yes. Split check uses approximate shard size | -| `security.shared_secret` | `""` | Yes. Empty is accepted only for loopback listeners. Non-empty requires the same bearer on gRPC and metrics | +| `security.shared_secret` | `""` | Yes. Empty does not start a listener. A non-empty value requires the same bearer on gRPC and metrics. Whitespace-only is rejected | +| `security.allow_unauthenticated` | `false` | Yes. Explicit loopback-only development opt-in. It does not allow a non-loopback bind, and it cannot be combined with a usable secret | There is no `[raft]` table. `ServerTomlConfig.raft_options` is skipped by serde and stays at `RaftNodeOptions::default()` (heartbeat 150 ms, election 450–900 ms, snapshot log keep 0, segment 64 MiB). @@ -71,13 +72,13 @@ CLI flags override the file after it is parsed: `--node-id`, `--cell-id`, `--rol This process does not terminate TLS. There is no certificate configuration that turns on native TLS. If the file contains a TLS, SSL, or certificate key, parsing fails and the process does not serve plaintext. Terminate TLS in an external proxy, and do not leave a TLS key in this file. -When `shared_secret` is non-empty, `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` require `authorization` to equal `Bearer ` exactly. `GET /metrics` on `metrics_listen_addr` requires the same `Authorization` header. A missing header, an empty bearer, a prefix, or a longer token is rejected. The metrics failure body is not Prometheus text. Raft peers send the same bearer. `metadb-ctl --auth-token` (environment variable `METADB_AUTH_TOKEN`) and `metadbd --join` / `--cell-manager` send it. `metadb-ctl cluster status` calls `GetRoutes` and is covered by that interceptor. +When `shared_secret` contains a non-whitespace character, `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` require `authorization` to equal `Bearer ` exactly. `GET /metrics` on `metrics_listen_addr` requires the same `Authorization` header. A missing header, an empty bearer, a prefix, or a longer token is rejected. The metrics failure body is not Prometheus text. Raft peers send the same bearer. `metadb-ctl --auth-token` (environment variable `METADB_AUTH_TOKEN`) and `metadbd --join` / `--cell-manager` send it. `metadb-ctl cluster status` calls `GetRoutes` and is covered by that interceptor. The client interceptor rejects a whitespace-only token instead of sending it. -An empty or whitespace-only secret is accepted only when `grpc_listen_addr` and `metrics_listen_addr` (if set) are loopback (`127.0.0.0/8`, `::1`, or the name `localhost`). A wildcard (`0.0.0.0`, `::`) or any other address refuses to listen. The code warns about an empty loopback secret at startup. The listeners are still plaintext. Keep them on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process. +An empty `shared_secret` does not start the process, including when every address is loopback. That is a compatibility change from the previous loopback default. Local development without credentials must set `allow_unauthenticated = true` and keep `grpc_listen_addr` and `metrics_listen_addr` (if set) on loopback (`127.0.0.0/8`, `::1`, or the unresolved name `localhost`). A wildcard (`0.0.0.0`, `::`) or any other address still refuses to listen. A whitespace-only secret is rejected even with that flag. Setting both a usable secret and `allow_unauthenticated` is rejected. The listeners are still plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process. -`empty_secret_on_loopback_serves_without_credentials` locks the current gap: `127.0.0.1` and an empty secret serve metadata, transactions, the control plane, and `GET /metrics` with no credentials. A `Basic` header is not consulted. A configured secret on that same loopback bind does not fail open: a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, and a wrong bearer are rejected, and the rejected create is not visible afterwards. A whitespace secret still starts on loopback, and an anonymous call is rejected rather than treated as no secret. +`empty_secret_on_loopback_does_not_listen` and `whitespace_secret_on_loopback_does_not_listen` cover those refusals. `explicit_unauthenticated_loopback_serves_without_credentials` covers the opt-in. A configured secret on loopback still rejects a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, and a wrong bearer, and the rejected create is not visible afterwards. -Unknown keys that do not name a secret or TLS setting remain a fail-open hole. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps the defaults, and serves. A `token_file` or `tls_mode` key still fails parsing. Closing that hole means rejecting those unknown keys, not teaching the server a new spelling. +Keys named like authentication or TLS (`anonymous`, `insecure`, `token_file`, `tls_mode`, and the same words nested in tables or arrays) fail parsing. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps those defaults, and serves only because that fixture also sets `allow_unauthenticated`. Closing the remaining unknown-key hole means rejecting those keys, not teaching the server a new spelling. ## What you cannot configure diff --git a/docs/en/operations.md b/docs/en/operations.md index ed6a819..d2ae604 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -73,7 +73,7 @@ The separate prefix-load harness (100 prefixes × 10,000 creates, then 100,000 ` ## Metrics -Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address. `GET /metrics` returns Prometheus text. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` is non-empty, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status`. A non-loopback metrics address with an empty secret refuses to start. This listener does not terminate TLS. +Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address. `GET /metrics` returns Prometheus text. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` is non-empty, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status`. An empty secret refuses to start on every address, including loopback, unless `allow_unauthenticated` is set. That flag still refuses a non-loopback metrics address. This listener does not terminate TLS. Gauges and counters from `render_prometheus_metrics`: @@ -141,7 +141,7 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. - Jumbo isolation is a route flag plus a node id chosen from the local node map. It does not evict other shards from a disk. - Heartbeats are an RPC with no sender in `metadbd`. `StoreHeartbeat` does not persist. -- A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret is accepted only for loopback binds and leaves those listeners unauthenticated. A wildcard bind with an empty secret refuses to start. The process does not terminate TLS. +- A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit loopback-only exception and still refuses a wildcard bind. A whitespace-only secret is rejected. The process does not terminate TLS. - `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. Raft timer fields do not change runtime behavior through TOML. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. diff --git a/docs/en/testing.md b/docs/en/testing.md index 7e29e86..de28957 100644 --- a/docs/en/testing.md +++ b/docs/en/testing.md @@ -126,12 +126,13 @@ Do not treat a number from this command as a repository result. It depends on th | `wildcard_without_a_secret_does_not_listen` | Wildcard gRPC or metrics bind with an empty or whitespace secret does not listen | | `misspelled_secret_and_tls_options_do_not_start` | A misspelled `shared_secret`, or a TLS key, fails parsing | | `configured_secret_rejects_missing_and_wrong_credentials` | Missing, empty, and wrong bearers are rejected on cluster status, lookup, Raft, and metrics | -| `empty_secret_on_loopback_serves_without_credentials` | `127.0.0.1` with an empty secret serves `GetRoutes`, `CreateFile`, `TransactionService.Rename`, and `GET /metrics` with no `Authorization` header. A `Basic` header and a garbage bearer are also accepted. This is the current local-development path | +| `empty_secret_on_loopback_does_not_listen` | `127.0.0.1` with an empty secret and `allow_unauthenticated = false` does not listen | +| `explicit_unauthenticated_loopback_serves_without_credentials` | The same loopback bind with `allow_unauthenticated = true` serves `GetRoutes`, `CreateFile`, `TransactionService.Rename`, and `GET /metrics` with no `Authorization` header. A `Basic` header is not consulted. This is the explicit local-development opt-in | | `configured_secret_rejects_basic_auth_without_applying_the_write` | On loopback, with a secret set, a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, the raw secret, and a wrong bearer return `Unauthenticated`. The rejected `CreateFile` is not visible to an authenticated lookup. Metrics with `Basic` returns HTTP 401 and no metric text | -| `whitespace_secret_on_loopback_rejects_anonymous_calls` | A whitespace secret still starts on loopback, and an anonymous call is rejected | +| `whitespace_secret_on_loopback_does_not_listen` | A whitespace-only secret does not start, including when `allow_unauthenticated` is set | | `unknown_toml_keys_are_ignored_and_loopback_still_serves` | `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn` are ignored. The process starts with the defaults and serves. `token_file` and `tls_mode` still fail parsing | -The empty-secret loopback result is a gap, not a pass of fail-closed authentication. A machine run that used `127.0.0.1` and an empty `shared_secret` did not exercise the wildcard refusal or a configured bearer. Unknown non-secret keys are also a gap: a typo in a storage or join field does not fail startup. This suite does not add TLS, mutual TLS, RBAC, a second metrics credential, or an audit log. Listeners stay plaintext. +An empty secret on loopback no longer serves. The opt-in above is the only unauthenticated path, and it is loopback-only. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored: a typo in a storage or join field does not fail startup. This suite does not add TLS, mutual TLS, RBAC, a second metrics credential, or an audit log. Listeners stay plaintext. ## Prefix load diff --git a/docs/guides/en/deployment.md b/docs/guides/en/deployment.md index 95cf61b..3d6b8aa 100644 --- a/docs/guides/en/deployment.md +++ b/docs/guides/en/deployment.md @@ -49,7 +49,7 @@ metadbd --config /etc/metadb/standalone.toml ### Network exposure -`MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` do **not** terminate TLS. Neither does the metrics listener. With an empty `[security].shared_secret` (the default) they perform no application authentication, and only loopback binds are accepted. A wildcard or other non-loopback address without a non-empty secret refuses to start. The default `grpc_listen_addr` is `127.0.0.1:7800`. A TLS or certificate key in this file is rejected rather than served as plaintext. +`MetadataService`, `TransactionService`, `ControlPlaneService`, `RaftTransportService`, and the metrics listener do **not** terminate TLS. An empty `[security].shared_secret` does not start the process, including on the default `127.0.0.1:7800` bind. Set `allow_unauthenticated = true` only for loopback development. A wildcard or other non-loopback address without a non-empty secret still refuses to start. A TLS, certificate, anonymous, or insecure key in this file is rejected rather than served as plaintext. Set a shared secret to require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: From 225f609349ca5ffd3cc25b388e18de64813065f9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 19:28:32 +0000 Subject: [PATCH 2/3] Correct English auth docs so examples match startup rules An empty secret is allowed only with the loopback opt-in. A whitespace-only secret is rejected even then. The loopback launch examples now include that explicit setting instead of a credential-free default. Co-authored-by: RustFS --- docs/en/architecture.md | 4 ++-- docs/en/build-and-run.md | 19 +++++++++++-------- docs/en/operations.md | 2 +- docs/en/testing.md | 2 +- docs/guides/en/deployment.md | 6 +++++- 5 files changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/en/architecture.md b/docs/en/architecture.md index de69b60..ac309b7 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -9,13 +9,13 @@ This page follows the code in `crates/`. It does not describe a multi-process Ce `PersistentMetaDbCluster::open_and_serve` (`crates/metadb-server/src/lib.rs`): 1. Rejects any `node.role` other than `all-in-one`. -2. Refuses to listen when `shared_secret` is empty or whitespace-only, unless `allow_unauthenticated` is set. That flag still refuses a wildcard or other non-loopback `grpc_listen_addr` or `metrics_listen_addr`. Then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port). +2. An empty `shared_secret` listens only when `allow_unauthenticated` is explicitly set, and only for loopback `grpc_listen_addr` and `metrics_listen_addr`. A whitespace-only secret is rejected even when that flag is set. The flag does not permit a wildcard or any other non-loopback address. Then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port). 3. Opens `DurableIdAllocator` at `/global_allocator`. 4. Opens `ShardGroupHost` at `/be`. 5. Opens or bootstraps `DurableCellManager` at `/cell_`. 6. Registers that one cell on `DurableGlobalManager` for the key range `[0x01, 0x04)`. 7. Ensures root directory inode `1` (`ROOT_INODE_ID`) has an attribute record. -8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A usable secret rejects a missing or wrong bearer. An empty secret listens only when `allow_unauthenticated` is set, and only on loopback. This process does not terminate TLS. +8. Serves four gRPC services on the same listener. All four take the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A secret that contains a non-whitespace character rejects a missing or wrong bearer. An empty secret listens only when `allow_unauthenticated` is set, and only on loopback. A whitespace-only secret does not reach this step. This process does not terminate TLS. 9. Spawns a maintenance task on a 250 ms interval. `metadbd` is a thin wrapper: it loads TOML, applies CLI overrides, calls `open_and_serve`, optionally calls `RegisterNode` on `--cell-manager`, and on Ctrl-C calls `shutdown`. Metrics, when configured, are served inside `open_and_serve`. diff --git a/docs/en/build-and-run.md b/docs/en/build-and-run.md index 5e5a44a..4136f9b 100644 --- a/docs/en/build-and-run.md +++ b/docs/en/build-and-run.md @@ -44,19 +44,22 @@ Debug builds use `cargo build -p metadb-server --bins` and write the same names Any role other than `all-in-one` fails before the listener is bound, with `server role ... is not implemented; only all-in-one runs a process`. -Example, loopback only: +Example, loopback only. `metadbd` with no config file uses an empty `shared_secret` and `allow_unauthenticated = false`, so that process does not start. The file below is the explicit loopback opt-in. It is not a credential. Do not use it on a non-loopback address. ```bash mkdir -p /tmp/metadb-data -cargo run -p metadb-server --bin metadbd -- \ - --data-dir /tmp/metadb-data \ - --listen 127.0.0.1:7800 \ - --node-id 1 \ - --cell-id 1 \ - --role all-in-one +cat > /tmp/metadb-loopback.toml <<'EOF' +[node] +data_dir = "/tmp/metadb-data" +grpc_listen_addr = "127.0.0.1:7800" + +[security] +allow_unauthenticated = true +EOF +cargo run -p metadb-server --bin metadbd -- --config /tmp/metadb-loopback.toml ``` -With a file, see [Configuration](./configuration.md): +A usable secret is a different configuration. Put a secret you choose in `shared_secret` and do not set `allow_unauthenticated` in that same file. Both together are rejected. See [Configuration](./configuration.md). ```bash cargo run -p metadb-server --bin metadbd -- --config ./standalone.toml diff --git a/docs/en/operations.md b/docs/en/operations.md index d2ae604..d2b755b 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -73,7 +73,7 @@ The separate prefix-load harness (100 prefixes × 10,000 creates, then 100,000 ` ## Metrics -Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address. `GET /metrics` returns Prometheus text. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` is non-empty, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status`. An empty secret refuses to start on every address, including loopback, unless `allow_unauthenticated` is set. That flag still refuses a non-loopback metrics address. This listener does not terminate TLS. +Set `node.metrics_listen_addr` (for example `127.0.0.1:9100`). `open_and_serve` accepts TCP connections on that address. `GET /metrics` returns Prometheus text. Any other path returns 404, and any other method returns 405. When `[security].shared_secret` contains a non-whitespace character, every request on this listener must send `Authorization: Bearer `. A missing, empty, or wrong bearer returns HTTP 401 and a body that is not the metric text, including a request for `/status`. An empty secret refuses to start on every address, including loopback, unless `allow_unauthenticated` is set. That flag still refuses a non-loopback metrics address. A whitespace-only secret refuses to start even when the flag is set. This listener does not terminate TLS. Gauges and counters from `render_prometheus_metrics`: diff --git a/docs/en/testing.md b/docs/en/testing.md index de28957..1fc6044 100644 --- a/docs/en/testing.md +++ b/docs/en/testing.md @@ -130,7 +130,7 @@ Do not treat a number from this command as a repository result. It depends on th | `explicit_unauthenticated_loopback_serves_without_credentials` | The same loopback bind with `allow_unauthenticated = true` serves `GetRoutes`, `CreateFile`, `TransactionService.Rename`, and `GET /metrics` with no `Authorization` header. A `Basic` header is not consulted. This is the explicit local-development opt-in | | `configured_secret_rejects_basic_auth_without_applying_the_write` | On loopback, with a secret set, a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, the raw secret, and a wrong bearer return `Unauthenticated`. The rejected `CreateFile` is not visible to an authenticated lookup. Metrics with `Basic` returns HTTP 401 and no metric text | | `whitespace_secret_on_loopback_does_not_listen` | A whitespace-only secret does not start, including when `allow_unauthenticated` is set | -| `unknown_toml_keys_are_ignored_and_loopback_still_serves` | `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn` are ignored. The process starts with the defaults and serves. `token_file` and `tls_mode` still fail parsing | +| `unknown_toml_keys_are_ignored_and_loopback_still_serves` | `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn` are ignored. The process starts and serves only because that fixture sets `allow_unauthenticated = true` with an empty secret and then binds `127.0.0.1`. Those unknown keys are not what opens the listener. `token_file` and `tls_mode` still fail parsing | An empty secret on loopback no longer serves. The opt-in above is the only unauthenticated path, and it is loopback-only. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored: a typo in a storage or join field does not fail startup. This suite does not add TLS, mutual TLS, RBAC, a second metrics credential, or an audit log. Listeners stay plaintext. diff --git a/docs/guides/en/deployment.md b/docs/guides/en/deployment.md index 3d6b8aa..53b45a3 100644 --- a/docs/guides/en/deployment.md +++ b/docs/guides/en/deployment.md @@ -37,6 +37,10 @@ locality_tombstone_ratio = 0.50 [sharding] bootstrap_table_shards = true # Shards 1 (Meta), 2 (Quota), 3 (SecondaryIndex) shard_split_threshold_bytes = 4294967296 # 4 GiB + +[security] +# Loopback development only. Remove this flag when you set shared_secret. +allow_unauthenticated = true ``` ### Launching Standalone Node @@ -51,7 +55,7 @@ metadbd --config /etc/metadb/standalone.toml `MetadataService`, `TransactionService`, `ControlPlaneService`, `RaftTransportService`, and the metrics listener do **not** terminate TLS. An empty `[security].shared_secret` does not start the process, including on the default `127.0.0.1:7800` bind. Set `allow_unauthenticated = true` only for loopback development. A wildcard or other non-loopback address without a non-empty secret still refuses to start. A TLS, certificate, anonymous, or insecure key in this file is rejected rather than served as plaintext. -Set a shared secret to require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: +To require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and `GET /metrics`, replace the `[security]` table above. Do not leave `allow_unauthenticated` in the file. A whitespace-only `shared_secret` is rejected even if that flag remains. Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: ```toml [security] From 8b276d3714ef8aef02179d93baefb1cdb0a933e1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 19:41:32 +0000 Subject: [PATCH 3/3] Reject hostname opt-in and stale non-loopback restart coverage Unauthenticated mode accepts only literal loopback IPs and rechecks the bound address, so localhost is not trusted. The saved-address regression opts in before asserting that refusal, and a separate test keeps the default empty-secret error. Security-sensitive key aliases fail closed. Co-authored-by: RustFS --- crates/metadb-server/src/config.rs | 58 ++++++++++++++----- crates/metadb-server/src/lib.rs | 12 +++- .../tests/security_adversarial_regressions.rs | 28 +++++++++ docs/en/architecture.md | 2 +- docs/en/build-and-run.md | 2 +- docs/en/configuration.md | 4 +- docs/en/operations.md | 2 +- docs/en/testing.md | 6 +- docs/guides/en/deployment.md | 2 +- 9 files changed, 93 insertions(+), 23 deletions(-) diff --git a/crates/metadb-server/src/config.rs b/crates/metadb-server/src/config.rs index 7683acb..afeffe3 100644 --- a/crates/metadb-server/src/config.rs +++ b/crates/metadb-server/src/config.rs @@ -236,16 +236,13 @@ impl ServerTomlConfig { } } -/// `true` only for an explicit loopback bind: `localhost`, `127.0.0.0/8`, or `::1`. +/// `true` only for a literal loopback IP: `127.0.0.0/8` or `::1`. /// -/// Wildcard addresses (`0.0.0.0`, `::`) and unparseable hosts are not loopback. -/// `localhost` is accepted as a name and is not resolved, so a hosts-file alias -/// is not detected here. +/// Hostnames, including `localhost`, are not loopback. They are not resolved, so +/// a hosts file cannot widen the unauthenticated opt-in, and startup does not +/// look the name up again at bind time. fn is_loopback_bind(addr: &str) -> bool { let host = bind_host(addr.trim()); - if host.eq_ignore_ascii_case("localhost") { - return true; - } match host.parse::() { Ok(ip) => ip.is_loopback(), Err(_) => false, @@ -286,7 +283,7 @@ fn normalize_key(key: &str) -> String { fn is_tls_key(key: &str) -> bool { let key = normalize_key(key); [ - "tls", "ssl", "cert", "x509", "mtls", "cipher", "keystore", "https", + "tls", "ssl", "cert", "x509", "mtls", "cipher", "keystore", "https", "ca_file", "cafile", ] .iter() .any(|needle| key.contains(needle)) @@ -303,6 +300,15 @@ fn is_secret_key(key: &str) -> bool { "auth", "anonymous", "insecure", + "api_key", + "apikey", + "bearer", + "jwt", + "private_key", + "privatekey", + "encryption", + "encrypt", + "anon", ] .iter() .any(|needle| key.contains(needle)) @@ -428,12 +434,7 @@ mod tests { whitespace.security.shared_secret = " ".into(); let mut configured = ServerTomlConfig::default(); configured.security.shared_secret = "secret".into(); - for addr in [ - "127.0.0.1:7800", - "127.0.0.1:0", - "localhost:7800", - "[::1]:7800", - ] { + for addr in ["127.0.0.1:7800", "127.0.0.1:0", "[::1]:7800"] { assert!(is_loopback_bind(addr), "{addr}"); assert!(opted_in.reject_unauthenticated_bind(addr).is_ok(), "{addr}"); let implicit_err = implicit.reject_unauthenticated_bind(addr).unwrap_err(); @@ -454,6 +455,7 @@ mod tests { "[::]:7800", "10.1.2.3:7800", "db.internal:7800", + "localhost:7800", ] { assert!(!is_loopback_bind(addr), "{addr}"); let err = opted_in.reject_unauthenticated_bind(addr).unwrap_err(); @@ -469,6 +471,34 @@ mod tests { assert!(both.to_string().contains("both set"), "{both}"); } + #[test] + fn security_sensitive_aliases_fail_closed_and_storage_keys_do_not() { + for key in [ + "api_key", + "bearer", + "jwt", + "private_key", + "ca_file", + "encryption", + "anon", + ] { + let parsed = ServerTomlConfig::from_toml_str(&format!("[node]\n{key} = \"x\"\n")); + let err = parsed.unwrap_err().to_string(); + assert!( + err.contains("refusing to start") && err.contains(key), + "{key}: {err}" + ); + } + let cfg = ServerTomlConfig::from_toml_str( + r#" + [storage] + bloom_bits_per_key = 12 + "#, + ) + .unwrap(); + assert_eq!(cfg.storage.bloom_bits_per_key, 12); + } + #[test] fn misspelled_secret_and_tls_keys_fail_closed() { let typo = ServerTomlConfig::from_toml_str( diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index bd2fbad..aa508a5 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -591,12 +591,17 @@ impl PersistentMetaDbCluster { if error.kind() == std::io::ErrorKind::AddrInUse && persisted_addr.is_some() => { // The saved port is busy. A sole voter can move; several voters cannot. - // `boot_local_shards` checks that after this bind. + // `boot_local_shards` checks that after this bind. Re-check the fallback + // string before binding it; do not resolve a hostname a second time. + config.reject_unauthenticated_bind(&config.node.grpc_listen_addr)?; TcpListener::bind(&config.node.grpc_listen_addr).await? } Err(error) => return Err(error.into()), }; let bound_addr = listener.local_addr()?.to_string(); + // The socket is already the address that was validated. This rejects a + // bound IP that is not literal loopback when no bearer is configured. + config.reject_unauthenticated_bind(&bound_addr)?; let clock = Arc::new(HybridLogicalClock::with_max_drift_ms( config.clock.max_clock_drift_ms, @@ -769,6 +774,11 @@ impl PersistentMetaDbCluster { return Err(error.into()); } }; + if let Err(error) = cluster.config.reject_unauthenticated_bind(&metrics_bound) { + drop(metrics_listener); + let _ = cluster.shutdown().await; + return Err(error); + } let _ = cluster.metrics_addr.set(metrics_bound.clone()); tracing::info!( metrics_addr = %metrics_bound, diff --git a/crates/metadb-server/tests/security_adversarial_regressions.rs b/crates/metadb-server/tests/security_adversarial_regressions.rs index 5e91610..fdd4c2c 100644 --- a/crates/metadb-server/tests/security_adversarial_regressions.rs +++ b/crates/metadb-server/tests/security_adversarial_regressions.rs @@ -40,6 +40,9 @@ async fn persisted_non_loopback_advertise_without_secret_fails_closed() { restart = with_data_dir(restart, dir.path()); restart.node.grpc_listen_addr = "127.0.0.1:0".into(); restart.security.shared_secret.clear(); + // Opt in so startup is not rejected for a missing secret before the saved + // non-loopback advertise address is considered. + restart.security.allow_unauthenticated = true; let err = match PersistentMetaDbCluster::open_and_serve(restart).await { Ok((cluster, _)) => { let _ = cluster.shutdown().await; @@ -58,6 +61,31 @@ async fn persisted_non_loopback_advertise_without_secret_fails_closed() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn default_empty_secret_is_rejected_before_any_listener() { + let mut cfg = ServerTomlConfig::default(); + cfg.node.data_dir = std::env::temp_dir().join("metadb-default-empty-secret"); + cfg.node.grpc_listen_addr = "127.0.0.1:9".into(); + cfg.security.shared_secret.clear(); + cfg.security.allow_unauthenticated = false; + let err = match PersistentMetaDbCluster::open_and_serve(cfg).await { + Ok((cluster, _)) => { + let _ = cluster.shutdown().await; + panic!("default empty secret must not start"); + } + Err(err) => err, + }; + let message = err.to_string(); + assert!( + message.contains("not an implicit exception"), + "empty-secret rejection was: {message}" + ); + assert!( + !message.contains("unauthenticated listener"), + "missing secret must fail before a recovered bind is considered: {message}" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn loopback_whitespace_secret_does_not_start() { // A whitespace-only secret used to start on loopback and accept only the diff --git a/docs/en/architecture.md b/docs/en/architecture.md index ac309b7..08b6f3b 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -9,7 +9,7 @@ This page follows the code in `crates/`. It does not describe a multi-process Ce `PersistentMetaDbCluster::open_and_serve` (`crates/metadb-server/src/lib.rs`): 1. Rejects any `node.role` other than `all-in-one`. -2. An empty `shared_secret` listens only when `allow_unauthenticated` is explicitly set, and only for loopback `grpc_listen_addr` and `metrics_listen_addr`. A whitespace-only secret is rejected even when that flag is set. The flag does not permit a wildcard or any other non-loopback address. Then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port). +2. An empty `shared_secret` listens only when `allow_unauthenticated` is explicitly set, and only when every listener address is a literal loopback IP (`127.0.0.0/8` or `::1`). The hostname `localhost` is not accepted and is not resolved. A whitespace-only secret is rejected even when that flag is set. The flag does not permit a wildcard or any other address. The process then binds that same literal address (`grpc_listen_addr` defaults to `127.0.0.1:7800`; port `0` asks the OS for a port). After the socket is bound, the bound IP is checked again. 3. Opens `DurableIdAllocator` at `/global_allocator`. 4. Opens `ShardGroupHost` at `/be`. 5. Opens or bootstraps `DurableCellManager` at `/cell_`. diff --git a/docs/en/build-and-run.md b/docs/en/build-and-run.md index 4136f9b..ffb2aed 100644 --- a/docs/en/build-and-run.md +++ b/docs/en/build-and-run.md @@ -67,7 +67,7 @@ cargo run -p metadb-server --bin metadbd -- --config ./standalone.toml Logs use `tracing-subscriber`'s `EnvFilter`. The default filter is `info`. Override it with the standard `RUST_LOG` variable, for example `RUST_LOG=debug`. -An empty `security.shared_secret` does not start the process. The default bind is `127.0.0.1`, and loopback is not an implicit exception. Local development without credentials sets `allow_unauthenticated = true` and keeps every listener on loopback. A wildcard or other non-loopback address still refuses to listen. A whitespace-only secret is rejected. A non-empty `[security].shared_secret` requires the same bearer on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the config fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. +An empty `security.shared_secret` does not start the process. The default bind is `127.0.0.1`, and loopback is not an implicit exception. Local development without credentials sets `allow_unauthenticated = true` and keeps every listener on a literal loopback IP (`127.0.0.1` or `::1`). The hostname `localhost` is not accepted for that opt-in. A wildcard or other non-loopback address still refuses to listen. A whitespace-only secret is rejected. A non-empty `[security].shared_secret` requires the same bearer on metadata, transaction, control-plane, Raft transport, and `GET /metrics`. The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the config fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates clients and block direct access to this process. Ctrl-C flushes shard state and stops the OpenRaft groups (`cluster.shutdown()`). diff --git a/docs/en/configuration.md b/docs/en/configuration.md index d5472a6..f90639a 100644 --- a/docs/en/configuration.md +++ b/docs/en/configuration.md @@ -74,11 +74,11 @@ This process does not terminate TLS. There is no certificate configuration that When `shared_secret` contains a non-whitespace character, `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` require `authorization` to equal `Bearer ` exactly. `GET /metrics` on `metrics_listen_addr` requires the same `Authorization` header. A missing header, an empty bearer, a prefix, or a longer token is rejected. The metrics failure body is not Prometheus text. Raft peers send the same bearer. `metadb-ctl --auth-token` (environment variable `METADB_AUTH_TOKEN`) and `metadbd --join` / `--cell-manager` send it. `metadb-ctl cluster status` calls `GetRoutes` and is covered by that interceptor. The client interceptor rejects a whitespace-only token instead of sending it. -An empty `shared_secret` does not start the process, including when every address is loopback. That is a compatibility change from the previous loopback default. Local development without credentials must set `allow_unauthenticated = true` and keep `grpc_listen_addr` and `metrics_listen_addr` (if set) on loopback (`127.0.0.0/8`, `::1`, or the unresolved name `localhost`). A wildcard (`0.0.0.0`, `::`) or any other address still refuses to listen. A whitespace-only secret is rejected even with that flag. Setting both a usable secret and `allow_unauthenticated` is rejected. The listeners are still plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process. +An empty `shared_secret` does not start the process, including when every address is loopback. That is a compatibility change from the previous loopback default. Local development without credentials must set `allow_unauthenticated = true` and keep `grpc_listen_addr` and `metrics_listen_addr` (if set) on a literal loopback IP (`127.0.0.0/8` or `::1`). The hostname `localhost` is not accepted for this opt-in and is not resolved, including through a hosts file. A usable secret may still bind a hostname. Compatibility: an opted-in config that used `localhost` no longer starts. A wildcard (`0.0.0.0`, `::`) or any other address still refuses to listen. A whitespace-only secret is rejected even with that flag. Setting both a usable secret and `allow_unauthenticated` is rejected. The listeners are still plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process. `empty_secret_on_loopback_does_not_listen` and `whitespace_secret_on_loopback_does_not_listen` cover those refusals. `explicit_unauthenticated_loopback_serves_without_credentials` covers the opt-in. A configured secret on loopback still rejects a missing header, `Authorization: Basic ...`, a lowercase `bearer` scheme, and a wrong bearer, and the rejected create is not visible afterwards. -Keys named like authentication or TLS (`anonymous`, `insecure`, `token_file`, `tls_mode`, and the same words nested in tables or arrays) fail parsing. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps those defaults, and serves only because that fixture also sets `allow_unauthenticated`. Closing the remaining unknown-key hole means rejecting those keys, not teaching the server a new spelling. +A key fails parsing when its normalized form (lowercase, hyphens become underscores) contains one of these substrings, including inside nested tables and arrays: `secret`, `password`, `passwd`, `token`, `credential`, `auth`, `anonymous`, `anon`, `insecure`, `api_key`, `apikey`, `bearer`, `jwt`, `private_key`, `privatekey`, `encryption`, `encrypt`, `tls`, `ssl`, `cert`, `x509`, `mtls`, `cipher`, `keystore`, `https`, `ca_file`, `cafile`, or it starts with `secur`. The only exceptions are the direct keys `[security].shared_secret` and `[security].allow_unauthenticated`. This is not a rejection of every unknown key. `bloom_bits_per_key` and a misspelled `grpc_listen_addr` or storage key are still ignored. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored. `unknown_toml_keys_are_ignored_and_loopback_still_serves` parses `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn`, keeps those defaults, and serves only because that fixture also sets `allow_unauthenticated`. Closing the remaining unknown-key hole means rejecting those keys, not teaching the server a new spelling. ## What you cannot configure diff --git a/docs/en/operations.md b/docs/en/operations.md index d2b755b..bea2185 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -141,7 +141,7 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. - Jumbo isolation is a route flag plus a node id chosen from the local node map. It does not evict other shards from a disk. - Heartbeats are an RPC with no sender in `metadbd`. `StoreHeartbeat` does not persist. -- A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit loopback-only exception and still refuses a wildcard bind. A whitespace-only secret is rejected. The process does not terminate TLS. +- A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit exception for literal loopback IPs (`127.0.0.0/8` or `::1`) and still refuses a wildcard bind. The hostname `localhost` is not accepted for that exception. A whitespace-only secret is rejected. The process does not terminate TLS. - `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. Raft timer fields do not change runtime behavior through TOML. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. diff --git a/docs/en/testing.md b/docs/en/testing.md index 1fc6044..f70f87b 100644 --- a/docs/en/testing.md +++ b/docs/en/testing.md @@ -119,11 +119,13 @@ Do not treat a number from this command as a repository result. It depends on th ## Fail-closed auth leftovers -`cargo test -p metadb-server --test auth_fail_closed` covers the listener checks from the fail-closed startup work, plus the cases a loopback run with an empty secret does not prove. +`cargo test -p metadb-server --test auth_fail_closed` covers the listener checks from the fail-closed startup work. `persisted_non_loopback_advertise_without_secret_fails_closed` and `default_empty_secret_is_rejected_before_any_listener` are in `security_adversarial_regressions.rs`. | Test | What it locks | | :--- | :--- | | `wildcard_without_a_secret_does_not_listen` | Wildcard gRPC or metrics bind with an empty or whitespace secret does not listen | +| `persisted_non_loopback_advertise_without_secret_fails_closed` | After a `0.0.0.0` process with a secret shuts down, restarting that directory with an empty secret and `allow_unauthenticated = true` on `127.0.0.1:0` still refuses the saved non-loopback address | +| `default_empty_secret_is_rejected_before_any_listener` | Default empty secret on `127.0.0.1` fails with the implicit-exception error and does not mention a recovered listener | | `misspelled_secret_and_tls_options_do_not_start` | A misspelled `shared_secret`, or a TLS key, fails parsing | | `configured_secret_rejects_missing_and_wrong_credentials` | Missing, empty, and wrong bearers are rejected on cluster status, lookup, Raft, and metrics | | `empty_secret_on_loopback_does_not_listen` | `127.0.0.1` with an empty secret and `allow_unauthenticated = false` does not listen | @@ -132,7 +134,7 @@ Do not treat a number from this command as a repository result. It depends on th | `whitespace_secret_on_loopback_does_not_listen` | A whitespace-only secret does not start, including when `allow_unauthenticated` is set | | `unknown_toml_keys_are_ignored_and_loopback_still_serves` | `grpc_listen_addrr`, `memtable_size_bytez`, and `joinn` are ignored. The process starts and serves only because that fixture sets `allow_unauthenticated = true` with an empty secret and then binds `127.0.0.1`. Those unknown keys are not what opens the listener. `token_file` and `tls_mode` still fail parsing | -An empty secret on loopback no longer serves. The opt-in above is the only unauthenticated path, and it is loopback-only. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored: a typo in a storage or join field does not fail startup. This suite does not add TLS, mutual TLS, RBAC, a second metrics credential, or an audit log. Listeners stay plaintext. +An empty secret on loopback no longer serves. The opt-in above is the only unauthenticated path, and it accepts only literal loopback IPs, not the hostname `localhost`. Unknown keys that do not name a secret, authentication, or TLS setting are still ignored: a typo in a storage or join field does not fail startup. This suite does not add TLS, mutual TLS, RBAC, a second metrics credential, or an audit log. Listeners stay plaintext. ## Prefix load diff --git a/docs/guides/en/deployment.md b/docs/guides/en/deployment.md index 53b45a3..3170894 100644 --- a/docs/guides/en/deployment.md +++ b/docs/guides/en/deployment.md @@ -53,7 +53,7 @@ metadbd --config /etc/metadb/standalone.toml ### Network exposure -`MetadataService`, `TransactionService`, `ControlPlaneService`, `RaftTransportService`, and the metrics listener do **not** terminate TLS. An empty `[security].shared_secret` does not start the process, including on the default `127.0.0.1:7800` bind. Set `allow_unauthenticated = true` only for loopback development. A wildcard or other non-loopback address without a non-empty secret still refuses to start. A TLS, certificate, anonymous, or insecure key in this file is rejected rather than served as plaintext. +`MetadataService`, `TransactionService`, `ControlPlaneService`, `RaftTransportService`, and the metrics listener do **not** terminate TLS. An empty `[security].shared_secret` does not start the process, including on the default `127.0.0.1:7800` bind. Set `allow_unauthenticated = true` only for development on a literal loopback IP such as `127.0.0.1`. The hostname `localhost` is not accepted for that flag. A wildcard or other non-loopback address without a non-empty secret still refuses to start. A TLS, certificate, anonymous, or insecure key in this file is rejected rather than served as plaintext. To require `authorization: Bearer ` on metadata, transaction, control-plane, Raft transport, and `GET /metrics`, replace the `[security]` table above. Do not leave `allow_unauthenticated` in the file. A whitespace-only `shared_secret` is rejected even if that flag remains. Peer Raft clients propagate the same token. `metadb-ctl --auth-token` (or `METADB_AUTH_TOKEN`) and `metadbd --cell-manager` send that header: