diff --git a/control/crates/layerfs-platform/tests/localhost_reach.rs b/control/crates/layerfs-platform/tests/localhost_reach.rs new file mode 100644 index 0000000000..be30bc4b6e --- /dev/null +++ b/control/crates/layerfs-platform/tests/localhost_reach.rs @@ -0,0 +1,48 @@ +//! A Linux `native` or `docker` Sandbox dials the Store URL exactly as the +//! caller and `store doctor` dial it: `localhost`, IP literals, `hostaddr`, +//! `verify-full`, host lists and Unix sockets all pass through unchanged. +#![cfg(target_os = "linux")] +#[path = "support/standin.rs"] +mod standin; +use layerfs_platform::{self as machine, Platform}; +use standin::Scratch; + +const SECRET: &str = "s3cr3t-pw"; + +fn urls() -> Vec { + [ + "postgresql://lfs:S@localhost/layerfs", + "postgres://lfs:S@localhost:5432/layerfs?sslmode=disable", + "postgres://lfs:S@LocalHost:5432/layerfs", + "postgres://lfs:S@127.0.0.1:5432/layerfs?sslmode=disable", + "postgres://lfs:S@[::1]:5432/layerfs?sslmode=disable", + "postgres://lfs:S@localhost:5432/layerfs?hostaddr=::1", + "postgres://lfs:S@localhost:5432/layerfs?hostaddr=127.0.0.1", + "postgres://lfs:S@localhost:5432/layerfs?sslmode=verify-full", + "postgres://lfs:S@127.0.0.1:5432/layerfs?sslmode=verify-full", + "postgres://lfs:S@[::1]:5432/layerfs?sslmode=verify-full", + "postgres://lfs:S@localhost:5432,[::1]:5433/layerfs", + "postgres://lfs:S@/layerfs?host=/var/run/postgresql", + "postgres://lfs:S@db.example.com:5432/layerfs?sslmode=verify-full", + ] + .iter() + .map(|u| u.replace(":S@", &format!(":{SECRET}@"))) + .collect() +} + +#[test] +fn native_and_docker_dial_every_url_as_given() { + let scratch = Scratch::new("reach-localhost"); + let mut changed = Vec::new(); + for kind in [Platform::Native, Platform::Docker] { + let spec = scratch.spec(kind); + for url in urls() { + let outcome = machine::reach(&spec, &url); + if outcome.as_deref() != Ok(url.as_str()) { + changed.push(format!("{kind:?} {url} -> {outcome:?}")); + } + } + } + assert!(changed.is_empty(), "{}", changed.join("\n")); + assert_eq!(scratch.log(), "", "no tool is asked for a shared loopback"); +} diff --git a/control/crates/layerfs-sandbox/src/launch/local.rs b/control/crates/layerfs-sandbox/src/launch/local.rs index c02e234ae0..9a0f55ac51 100644 --- a/control/crates/layerfs-sandbox/src/launch/local.rs +++ b/control/crates/layerfs-sandbox/src/launch/local.rs @@ -146,6 +146,14 @@ fn start_named( let labels = crate::lifecycle::labels(name, store.as_deref(), id); let api = SandboxApi::with_runtime(Arc::new(runtime)); let options = launch_options(backend, identity, host)?; + let pg_host = match &setup.store { + DaemonStore::Postgres { url, .. } => Some( + layerfs_sandbox_backend::PostgresUrl::parse(url) + .map(|parsed| parsed.host().to_owned()) + .unwrap_or_default(), + ), + DaemonStore::Sqlite { .. } => None, + }; let request = ProviderCreate { launch: LaunchRequest { name: sandbox_name.clone(), @@ -169,6 +177,16 @@ fn start_named( }; let created = created.map_err(|mut failure| { drop(failure.control.take()); + let pg = pg_host + .as_deref() + .filter(|_| failure.phase == crate::SandboxPhase::Listener) + .map(|pg_host| { + ( + pg_host, + host.store.as_str(), + backend == crate::runtime::Backend::Namespaces, + ) + }); abandon( id, format!( @@ -178,6 +196,7 @@ fn start_named( ), failure.runtime.take(), &executable, + pg, ) })?; let instance = created.startup.instance; @@ -193,6 +212,7 @@ fn start_named( ), Some(sandbox), &executable, + None, )); } }; @@ -238,6 +258,7 @@ fn start_named( ), runtime, &executable, + None, )); } let state = Arc::new(state); @@ -433,15 +454,18 @@ fn abandon( mut cause: String, sandbox: Option>, daemon: &Path, + pg: Option<(&str, &str, bool)>, ) -> SdkRefusal { let container = sandbox.as_ref().map(|s| s.identity().to_string()); let mut log = None; + let mut last_line = None; let mut left = None; if let Some(mut sandbox) = sandbox { match sandbox.log_tail(crate::lifecycle::LOG_LINES, crate::lifecycle::LOG_BYTES) { Ok(bytes) => { let text = String::from_utf8_lossy(&bytes).trim_end().to_owned(); if let Some(last) = text.lines().rev().map(str::trim).find(|l| !l.is_empty()) { + last_line = Some(last.to_owned()); cause = format!("{cause}. Its daemon's last error: {last}"); } log = Some(text); @@ -456,9 +480,34 @@ fn abandon( ) }); } - let (code, message, removed) = match left { - None => ("Failed", cause, container.is_some()), - Some(left) => ( + let pg_unreachable = left.is_none() + && pg.is_some() + && last_line.as_deref().is_some_and(|line| { + line.contains("cannot reach PostgreSQL Store") + || line.contains("Store open: physical Store I/O: pack persistence: Refused { status: \"Closed\" }") + }); + let (code, message, removed) = match (left, pg_unreachable, pg) { + (None, true, Some((pg_host, store_name, namespaces))) => { + let message = if pg_host.is_empty() { + format!( + "Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server" + ) + } else if namespaces + && !pg_host.eq_ignore_ascii_case("localhost") + && pg_host.parse::().is_err() + { + format!( + "Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server at {pg_host} (the Sandbox root has no /etc/hosts or /etc/resolv.conf, so a hostname may not resolve there; use an IP address)" + ) + } else { + format!( + "Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server at {pg_host}" + ) + }; + ("Unavailable", message, container.is_some()) + } + (None, _, _) => ("Failed", cause, container.is_some()), + (Some(left), _, _) => ( "Unknown", format!("creation of Sandbox {id} failed ({cause}); {left}"), false, diff --git a/docs/architecture/api/sdk/sandbox.md b/docs/architecture/api/sdk/sandbox.md index 0c290b6ffc..dee27af379 100644 --- a/docs/architecture/api/sdk/sandbox.md +++ b/docs/architecture/api/sdk/sandbox.md @@ -112,8 +112,13 @@ A create whose outcome is not known is `Unknown`; its record keeps the A start that fails is `Failed` in words: "Sandbox `` did not start: it stopped ``: ``", then "Its daemon's last error: …" from -its log. Its `detail` holds `daemon` (the program that was started), -`log` (its last lines), `container` and `removed` +its log, except when a PostgreSQL Sandbox daemon could not reach its +Store's server at startup (`Unavailable`: "Sandbox `` did not start: +its daemon cannot reach PostgreSQL Store ``'s server at ``", +noting on `namespaces` when `` is a hostname that the Sandbox root +has no `/etc/hosts` or `/etc/resolv.conf`). Its `detail` holds `daemon` +(the program that was started), `log` (its last lines), `container` and +`removed` ([`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs) `abandon`). Its `fix` is `layerfs machine doctor ` unless the refusal names a closer one. On `native`, when `detail.daemon` is the native machine's diff --git a/docs/architecture/engine/store/postgresql.md b/docs/architecture/engine/store/postgresql.md index 272f130a85..9339cdfe84 100644 --- a/docs/architecture/engine/store/postgresql.md +++ b/docs/architecture/engine/store/postgresql.md @@ -81,7 +81,10 @@ including a server silent past the 5 s connect-and-login limit connection is dialled on its own thread and waited for within that limit; a dial left waiting ends when the server answers or the socket closes. The diagnostic driver gives its connect and login the same limit under a longer -deadline. The +deadline. `Connector::new` pairs a single `localhost` host (with no +`hostaddr`) with `127.0.0.1` and `::1` via `hostaddr` while keeping +`localhost` for TLS verification, so roots without `/etc/hosts` reach +either IPv4 or IPv6 loopback without DNS. The session keeps the frozen policy and server version the open check read, so `PackPersistence::policy` costs no round trip afterwards. `compaction_missing(session)` applies the same five Store-wide checks to the diff --git a/engine/crates/layerfs-daemon/src/application/failure.rs b/engine/crates/layerfs-daemon/src/application/failure.rs index 37e3e7e774..920896bffc 100644 --- a/engine/crates/layerfs-daemon/src/application/failure.rs +++ b/engine/crates/layerfs-daemon/src/application/failure.rs @@ -21,6 +21,11 @@ pub enum ApplicationError { }, /// Original direct existing-Store open failure. Store(layerfs_storage::StorageError), + /// PostgreSQL Store server was unreachable at open. + PostgresUnreachable { + /// Server host without userinfo. + host: String, + }, /// Original authentication/kernel transport failure. Channel(ChannelError), /// Original malformed request, with bounded bytes retained separately. @@ -53,6 +58,12 @@ impl fmt::Display for ApplicationError { Self::Owner(e) => write!(f, "Overlay startup: {:?}", e.result.as_ref().err()), Self::AfterOverlay { cause, .. } => write!(f, "after Overlay startup: {cause}"), Self::Store(e) => write!(f, "Store open: {e}"), + Self::PostgresUnreachable { host } if host.is_empty() => { + f.write_str("cannot reach PostgreSQL Store") + } + Self::PostgresUnreachable { host } => { + write!(f, "cannot reach PostgreSQL Store at {host}") + } Self::Channel(e) => write!(f, "kernel channel: {e}"), Self::Protocol(e) => write!(f, "kernel request: {e}"), Self::Install(e) => write!(f, "installation: {e}"), diff --git a/engine/crates/layerfs-daemon/src/application/owner.rs b/engine/crates/layerfs-daemon/src/application/owner.rs index edf01f513c..f883310f30 100644 --- a/engine/crates/layerfs-daemon/src/application/owner.rs +++ b/engine/crates/layerfs-daemon/src/application/owner.rs @@ -566,10 +566,29 @@ impl Application { Some(opened) } Err(cause) => { + let closed = matches!( + &cause, + layerfs_storage::StorageError::Io(io) + if matches!( + io.get_ref().and_then(|e| { + e.downcast_ref::() + }), + Some(layerfs_storage::port::PersistenceError::Refused { status }) + if status == "Closed" + ) + ); + let cause = match (&setup.store, closed) { + (layerfs_bridge::DaemonStore::Postgres { url, .. }, true) => { + ApplicationError::PostgresUnreachable { + host: postgres_host(url), + } + } + _ => ApplicationError::Store(cause), + }; return Err(ApplicationError::AfterOverlay { owner: Box::new(owner), - cause: Box::new(ApplicationError::Store(cause)), - }) + cause: Box::new(cause), + }); } }, None => None, @@ -710,6 +729,23 @@ impl Application { /// server. A Sandbox daemon opens it with the light check (#63): the schema /// was fully checked when its Store was connected, and the caller's reach /// check read its binding just before this daemon started. +fn postgres_host(url: &str) -> String { + let Some((_, rest)) = url.split_once("://") else { + return String::new(); + }; + let authority = rest.split(['/', '?']).next().unwrap_or(""); + let host_port = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + match host_port.strip_prefix('[') { + Some(v6) => v6.split_once(']').map_or("", |(host, _)| host).to_owned(), + None => host_port + .rsplit_once(':') + .map_or(host_port, |(host, _)| host) + .to_owned(), + } +} + fn postgres(url: &str, schema: &str, synchronous_commit: &str) -> PostgresSelection { let setting = match synchronous_commit { "local" => SynchronousCommit::Local, diff --git a/engine/crates/layerfs-daemon/tests/postgres_unreachable.rs b/engine/crates/layerfs-daemon/tests/postgres_unreachable.rs new file mode 100644 index 0000000000..8ae29f7492 --- /dev/null +++ b/engine/crates/layerfs-daemon/tests/postgres_unreachable.rs @@ -0,0 +1,98 @@ +//! A daemon whose PostgreSQL Store server cannot be reached exits with a +//! clear `cannot reach PostgreSQL Store at ` message instead of raw +//! `pack persistence: Refused { status: "Closed" }` debug text, and never +//! includes the URL password. +#![cfg(any(target_os = "linux", target_os = "macos"))] + +use layerfs_bridge::{ + daemon_setup::{DaemonLimits, DaemonSetup}, + duplex, DaemonStore, KernelRoute, StoreAuthority, +}; +use std::{ + fs::{self, File}, + net::TcpListener, + os::unix::fs::{MetadataExt, PermissionsExt}, + path::PathBuf, + process::{Command, Stdio}, + sync::atomic::{AtomicU64, Ordering}, +}; + +static NEXT: AtomicU64 = AtomicU64::new(0); +const SECRET: &str = "s3cr3t-pg-pw"; + +fn tempdir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "layerfs-daemon-pg-unreach-{tag}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +#[test] +fn daemon_reports_unreachable_postgres_store_without_pack_persistence_debug_text() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let closed_port = listener.local_addr().unwrap().port(); + drop(listener); + + let dir = tempdir("closed"); + let mounts = dir.join("mounts"); + fs::create_dir_all(&mounts).unwrap(); + fs::set_permissions(&mounts, fs::Permissions::from_mode(0o700)).unwrap(); + let id = fs::metadata(&dir).unwrap(); + let setup = DaemonSetup { + listen: "127.0.0.1:0".into(), + private_key: [72; 32], + control_peer: duplex::public_key(&[71; 32]).unwrap(), + route: KernelRoute::Nfs, + overlay: dir.join("overlay.sqlite").display().to_string(), + mounts: mounts.display().to_string(), + command_uid: id.uid(), + command_gid: id.gid(), + limits: DaemonLimits { + connections: 4, + handshake_ms: 2000, + idle_ttl_ms: 60_000, + request_deadline_ms: 60_000, + cache_bytes: 1024 * 1024, + namespaces: 4, + pager_kib: 1024, + serial_low_water: 256, + }, + store: DaemonStore::Postgres { + url: format!("postgres://app:{SECRET}@127.0.0.1:{closed_port}/shop?sslmode=disable"), + schema: "layerfs".to_owned(), + synchronous_commit: "local".to_owned(), + authority: StoreAuthority { + binding: vec![1; 16], + cursor_key: [2; 32], + }, + }, + }; + let config = dir.join("daemon.config"); + fs::write(&config, setup.encode().unwrap()).unwrap(); + fs::set_permissions(&config, fs::Permissions::from_mode(0o600)).unwrap(); + let stderr_path = dir.join("daemon.stderr"); + let status = Command::new(env!("CARGO_BIN_EXE_layerfs-daemon")) + .arg("--config") + .arg(&config) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::from(File::create(&stderr_path).unwrap())) + .status() + .expect("run layerfs-daemon"); + let stderr = fs::read_to_string(&stderr_path).unwrap(); + let _ = fs::remove_dir_all(&dir); + + assert!(!status.success(), "expected failure: {stderr}"); + assert!( + stderr.contains("cannot reach PostgreSQL Store at 127.0.0.1"), + "{stderr}" + ); + assert!(!stderr.contains("pack persistence"), "{stderr}"); + assert!(!stderr.contains("Refused"), "{stderr}"); + assert!(!stderr.contains(SECRET), "{stderr}"); +} diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs index 686934a290..787613bff2 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs @@ -5,11 +5,13 @@ use crate::backend::{admission::Admission, records::BackendError}; use crate::{PostgresSelection, SqlWork}; use layerfs_storage::StoragePolicy; use postgres::{ - config::SslMode, Client, Config, NoTls, SimpleQueryMessage, SimpleQueryRow, Statement, + config::{Host, SslMode}, + Client, Config, NoTls, SimpleQueryMessage, SimpleQueryRow, Statement, }; use postgres_native_tls::MakeTlsConnector; use std::{ collections::HashMap, + net::{IpAddr, Ipv4Addr, Ipv6Addr}, str::FromStr, sync::{ atomic::{AtomicI64, AtomicU64, Ordering}, @@ -75,7 +77,17 @@ pub(crate) struct Connector { impl Connector { pub(crate) fn new(selection: &PostgresSelection) -> Result { - let config = Config::from_str(&selection.url).map_err(|_| BackendError::Integrity)?; + let mut config = Config::from_str(&selection.url).map_err(|_| BackendError::Integrity)?; + if config.get_hostaddrs().is_empty() { + if let [Host::Tcp(host)] = config.get_hosts() { + if host.eq_ignore_ascii_case("localhost") { + let name = host.clone(); + config.host(&name); + config.hostaddr(IpAddr::V4(Ipv4Addr::LOCALHOST)); + config.hostaddr(IpAddr::V6(Ipv6Addr::LOCALHOST)); + } + } + } let tls = match config.get_ssl_mode() { SslMode::Disable => None, _ => Some(tls()?), diff --git a/engine/crates/layerfs-persistence/tests/postgresql_localhost.rs b/engine/crates/layerfs-persistence/tests/postgresql_localhost.rs new file mode 100644 index 0000000000..aff6726fb8 --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/postgresql_localhost.rs @@ -0,0 +1,159 @@ +//! A Store URL whose host is `localhost` reaches a server on either loopback, +//! even where `localhost` does not resolve (a Sandbox root without +//! `/etc/hosts`); IP literals, a given `hostaddr`, Unix sockets and other +//! host names are dialled as given. Needs `LAYERFS_TEST_PG_LOOPBACK_URL` +//! (`postgres://user:pw@localhost:/`, no query) and +//! `LAYERFS_TEST_PG_LOOPBACK_LISTEN` (`127.0.0.1` or `::1`, the only address +//! the server listens on); NOT_RUN without them. With +//! `LAYERFS_TEST_PG_LOOPBACK_TLS=1` the server's certificate names only +//! `localhost` and is trusted through `SSL_CERT_FILE`. +use layerfs_history::HistoryCatalogConfig; +use layerfs_persistence::{PostgresHandles, PostgresSelection}; +use layerfs_storage::{port::PersistenceError, StoragePolicy}; + +struct Server { + url: String, + listen: &'static str, + other: &'static str, +} + +fn server() -> Option { + let (Ok(url), Ok(listen)) = ( + std::env::var("LAYERFS_TEST_PG_LOOPBACK_URL"), + std::env::var("LAYERFS_TEST_PG_LOOPBACK_LISTEN"), + ) else { + eprintln!("NOT_RUN: LAYERFS_TEST_PG_LOOPBACK_URL or _LISTEN is unset"); + return None; + }; + assert!(url.contains("@localhost:") && !url.contains('?'), "{url}"); + let (listen, other) = match listen.as_str() { + "127.0.0.1" => ("127.0.0.1", "[::1]"), + "::1" => ("[::1]", "127.0.0.1"), + other => panic!("LAYERFS_TEST_PG_LOOPBACK_LISTEN={other}"), + }; + Some(Server { url, listen, other }) +} + +impl Server { + fn with_host(&self, host: &str, query: &str) -> String { + let url = self.url.replace("@localhost:", &format!("@{host}:")); + format!("{url}?{query}") + } + fn port(&self) -> &str { + let tail = self.url.rsplit_once(':').unwrap().1; + tail.split('/').next().unwrap() + } +} + +fn create(url: &str, tag: &str) -> Result<(), PersistenceError> { + let schema = format!("lfs_lh_{tag}_{}", std::process::id()); + let selection = PostgresSelection::new(url, &schema); + let made = PostgresHandles::create( + &selection, + StoragePolicy::frozen_default(), + &HistoryCatalogConfig { + binding_key: b"postgresql-localhost".to_vec(), + cursor_key: [7; 32], + incarnation: 1, + }, + ); + let made = made.map(drop); + if made.is_ok() { + PostgresHandles::open_read_only(&selection, b"postgresql-localhost", [7; 32])?; + } + made +} + +fn drop_schema(server: &Server, tag: &str) { + let admin = server.with_host(server.listen, "sslmode=disable"); + if let Ok(mut client) = postgres::Client::connect(&admin, postgres::NoTls) { + let schema = format!("lfs_lh_{tag}_{}", std::process::id()); + let _ = client.batch_execute(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE")); + } +} + +fn reaches(server: &Server, url: &str, tag: &str) -> Result<(), PersistenceError> { + let made = create(url, tag); + drop_schema(server, tag); + made +} + +#[test] +fn localhost_reaches_the_server_on_its_loopback() { + let Some(s) = server() else { return }; + for (i, host) in ["localhost", "LocalHost"].into_iter().enumerate() { + let url = s.with_host(host, "sslmode=disable"); + reaches(&s, &url, &format!("name{i}")).unwrap(); + } +} + +#[test] +fn ip_literals_are_dialled_as_given() { + let Some(s) = server() else { return }; + reaches(&s, &s.with_host(s.listen, "sslmode=disable"), "lit_listen").unwrap(); + let other = s.with_host(s.other, "sslmode=disable&connect_timeout=5"); + assert!(reaches(&s, &other, "lit_other").is_err(), "{}", s.other); +} + +#[test] +fn a_given_hostaddr_is_kept() { + let Some(s) = server() else { return }; + let bare = |h: &str| h.trim_matches(['[', ']']).to_owned(); + let listen = format!("sslmode=disable&hostaddr={}", bare(s.listen)); + reaches(&s, &s.with_host("localhost", &listen), "addr_listen").unwrap(); + let other = format!( + "sslmode=disable&connect_timeout=5&hostaddr={}", + bare(s.other) + ); + let outcome = reaches(&s, &s.with_host("localhost", &other), "addr_other"); + assert!(outcome.is_err(), "hostaddr={} was not kept", s.other); +} + +#[test] +fn another_host_name_or_a_socket_gets_no_loopback() { + let Some(s) = server() else { return }; + let url = s.with_host( + "lfs-no-such-host.invalid", + "sslmode=disable&connect_timeout=5", + ); + assert!(reaches(&s, &url, "name_other").is_err()); + let user = s + .url + .split("//") + .nth(1) + .unwrap() + .split([':', '@']) + .next() + .unwrap(); + let socket = format!( + "host=/nonexistent-lfs-socket port={} user={user} dbname=postgres sslmode=disable connect_timeout=5", + s.port() + ); + assert!(reaches(&s, &socket, "socket").is_err()); +} + +#[test] +fn verify_full_is_refused_as_before() { + let Some(s) = server() else { return }; + let url = s.with_host("localhost", "sslmode=verify-full"); + assert_eq!( + reaches(&s, &url, "verify_full").unwrap_err(), + PersistenceError::Malformed + ); +} + +#[test] +fn tls_checks_the_name_localhost() { + let Some(s) = server() else { return }; + if std::env::var("LAYERFS_TEST_PG_LOOPBACK_TLS").as_deref() != Ok("1") { + eprintln!("NOT_RUN: LAYERFS_TEST_PG_LOOPBACK_TLS is not 1"); + return; + } + reaches(&s, &s.with_host("localhost", "sslmode=require"), "tls_name").unwrap(); + let literal = s.with_host(s.listen, "sslmode=require&connect_timeout=5"); + assert!( + reaches(&s, &literal, "tls_literal").is_err(), + "a certificate naming only localhost must not pass for {}", + s.listen + ); +}