From 5276f5c33e4a879854ce408062d126f7bf40eadb Mon Sep 17 00:00:00 2001 From: liuyuchen <152110621+jiangkoumo@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:15:38 +0000 Subject: [PATCH 1/3] fix(platform,daemon,sandbox): rewrite localhost to 127.0.0.1 on Linux shared loopback and clarify unreachable PostgreSQL daemon open errors On Linux, both `native` and `docker` machines use `Loopback::Shared` in `reach.rs` and run their Sandbox daemons inside `namespaces` roots pivoted to an unpacked image without `/etc/hosts` or `/etc/resolv.conf` (`image_tar/filter.rs` drops init files). `store.reach` and `reach_check` ran in the host or worker container where `localhost` resolved, so `store doctor` reported ok while `sandbox create` failed inside the daemon with `Store open: physical Store I/O: pack persistence: Refused { status: "Closed" }` and suggested `layerfs machine doctor`. - `layerfs-platform/src/reach.rs`: under `Loopback::Shared` on Linux, rewrite `localhost` to `127.0.0.1` (refusing `sslmode=verify-full` as `Unsupported`, matching other rewrites). Keep `127.0.0.1`, `[::1]`, `?host=`/`?hostaddr=`, Unix sockets, non-loopback hosts, and macOS `native` unchanged. - `layerfs-daemon`: map PostgreSQL `PersistenceError::Refused { status: "Closed" }` at Store open to `ApplicationError::PostgresUnreachable { host }` (`cannot reach PostgreSQL Store at `, without userinfo). - `layerfs-sandbox/src/launch/local.rs`: translate PostgreSQL Store-open unreachable failures in `abandon` to `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`, instead of exposing `pack persistence: Refused` and suggesting `machine doctor`. - Docs: update `workers-and-reach.md`, `platforms.md`, and `sandbox.md`. Tests: added `engine/crates/layerfs-daemon/tests/postgres_unreachable.rs` and `control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs`; updated `layerfs-platform` `machine_reach` and `conformance` for Linux `Shared` `localhost` rewriting. Both new tests failed on `ed9118963` and pass on this fix. No test deleted; no assertion weakened. Production LOC: 205844 -> 205950 (delta +106); core 40988, engine 95845 -> 95889 (layerfs-daemon 9024 -> 9068), control 58745 -> 58807 (layerfs-platform 3692 -> 3708, layerfs-sandbox 17117 -> 17163), api 10266. Scope and method: tools/production_loc.py --root --json on git archive extracts of ed9118963 and HEAD tree b9aea00e0e9123c749a7bfc4c09547b6efeecd66. Reference absent (retired R9c; last counted 65,417 at tree 498dd1917812). --- .../src/platforms/docker/adapter.rs | 9 +- control/crates/layerfs-platform/src/reach.rs | 36 +++++-- .../layerfs-platform/tests/conformance.rs | 16 ++- .../layerfs-platform/tests/machine_reach.rs | 33 +++++-- .../layerfs-sandbox/src/launch/local.rs | 52 +++++++++- .../tests/postgres_reach_localhost.rs | 96 ++++++++++++++++++ docs/architecture/api/sdk/sandbox.md | 9 +- .../control/machines/platforms.md | 2 +- .../control/machines/workers-and-reach.md | 10 +- .../layerfs-daemon/src/application/failure.rs | 11 +++ .../layerfs-daemon/src/application/owner.rs | 40 +++++++- .../tests/postgres_unreachable.rs | 98 +++++++++++++++++++ 12 files changed, 379 insertions(+), 33 deletions(-) create mode 100644 control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs create mode 100644 engine/crates/layerfs-daemon/tests/postgres_unreachable.rs diff --git a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs index 03f8b44d35..1a9a3f760c 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs @@ -82,11 +82,10 @@ impl Adapter for Docker { status(spec) } /// On a Linux Engine the worker shares the host's network, and its - /// `namespaces` Sandboxes share the worker's (D-8), so a loopback URL is - /// dialled as given. Elsewhere (Docker Desktop) a loopback URL becomes - /// the address the running worker container resolves - /// `host.docker.internal` to: a Sandbox image's root cannot resolve - /// the name. + /// `namespaces` Sandboxes share the worker's (D-8), though their image + /// root has no `/etc/hosts` so `localhost` becomes `127.0.0.1`. Elsewhere + /// (Docker Desktop) a loopback URL becomes the address the running worker + /// container resolves `host.docker.internal` to. fn reach(&self, spec: &Spec, url: &str) -> Result { if cfg!(target_os = "linux") { return dial(spec, url, Loopback::Shared); diff --git a/control/crates/layerfs-platform/src/reach.rs b/control/crates/layerfs-platform/src/reach.rs index 11a5968aaf..2926aff786 100644 --- a/control/crates/layerfs-platform/src/reach.rs +++ b/control/crates/layerfs-platform/src/reach.rs @@ -24,19 +24,27 @@ pub(crate) enum Loopback<'a> { /// The URL `spec`'s daemon dials for `url`, given how its machine reaches /// the caller's loopback. pub(crate) fn dial(spec: &Spec, url: &str, loopback: Loopback<'_>) -> Result { - if let Loopback::Shared = loopback { + let shared_linux = matches!(loopback, Loopback::Shared) && cfg!(target_os = "linux"); + if matches!(loopback, Loopback::Shared) && !shared_linux { return Ok(url.to_owned()); } // a host list (`h1:5432,h2:5433`) reads as one host holding a `,` let parsed = PostgresUrl::parse(url).filter(|p| !p.host().contains(',')); - let parsed = parsed.ok_or_else(|| { - refuse( - spec, - Code::InvalidInput, - "its URL is not one postgres://[user@]host[:port]/... URL with one host", - ) - })?; + let parsed = match parsed { + Some(parsed) => parsed, + None if shared_linux => return Ok(url.to_owned()), + None => { + return Err(refuse( + spec, + Code::InvalidInput, + "its URL is not one postgres://[user@]host[:port]/... URL with one host", + )); + } + }; if parsed.query("host").chain(parsed.query("hostaddr")).count() > 0 { + if shared_linux { + return Ok(url.to_owned()); + } return Err(refuse( spec, Code::Unsupported, @@ -44,13 +52,21 @@ pub(crate) fn dial(spec: &Spec, url: &str, loopback: Loopback<'_>) -> Result) -> Result "127.0.0.1".to_owned(), Loopback::Alias(alias) => alias.to_owned(), Loopback::Lookup(read) => read()?, - Loopback::Shared => unreachable!("answered above"), }; Ok(parsed.with_host(&alias)) } diff --git a/control/crates/layerfs-platform/tests/conformance.rs b/control/crates/layerfs-platform/tests/conformance.rs index 64b80ec9c6..c8a094d50d 100644 --- a/control/crates/layerfs-platform/tests/conformance.rs +++ b/control/crates/layerfs-platform/tests/conformance.rs @@ -426,6 +426,11 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { for (i, url) in loopback_urls(query).iter().enumerate() { let outcome = machine::reach(&spec, url); match loopback(&spec) { + Loopback::Shared if cfg!(target_os = "linux") && i == 1 => assert_eq!( + outcome, + Ok(with_host("127.0.0.1", query)[1].clone()), + "{platform:?}" + ), Loopback::Shared => assert_eq!(outcome.as_ref(), Ok(url)), Loopback::Alias(alias) => assert_eq!( outcome, @@ -436,9 +441,18 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { } } // the server's certificate names the loopback host, not an alias - for url in loopback_urls("?sslmode=verify-full") { + for (i, url) in loopback_urls("?sslmode=verify-full") + .into_iter() + .enumerate() + { let outcome = machine::reach(&spec, &url); match loopback(&spec) { + Loopback::Shared if cfg!(target_os = "linux") && i == 1 => { + let (code, message) = refused(platform, outcome); + assert_eq!(code, Code::Unsupported, "{message}"); + assert!(message.starts_with(&prefix), "{message}"); + assert!(message.contains("sslmode=verify-full"), "{message}"); + } Loopback::Shared => assert_eq!(outcome, Ok(url)), Loopback::Alias(_) => { let (code, message) = refused(platform, outcome); diff --git a/control/crates/layerfs-platform/tests/machine_reach.rs b/control/crates/layerfs-platform/tests/machine_reach.rs index f0fb37e49f..a89d4d448f 100644 --- a/control/crates/layerfs-platform/tests/machine_reach.rs +++ b/control/crates/layerfs-platform/tests/machine_reach.rs @@ -74,6 +74,11 @@ fn each_platform_rewrites_a_loopback_host() { for (i, url) in loopback_urls().iter().enumerate() { let outcome = machine::reach(&spec, url); match alias { + // Linux namespaces Sandboxes have no /etc/hosts, so localhost + // becomes 127.0.0.1 while 127.0.0.1 and [::1] stay unchanged. + "unchanged" if cfg!(target_os = "linux") && i == 1 => { + assert_eq!(outcome, Ok(rewritten("127.0.0.1")[1].clone()), "{kind:?}") + } "unchanged" => assert_eq!(outcome.as_deref(), Ok(url.as_str())), alias => assert_eq!(outcome, Ok(rewritten(alias)[i].clone()), "{kind:?}"), } @@ -155,7 +160,7 @@ fn a_rewrite_is_refused_for_verify_full() { let scratch = Scratch::new("reach-tls"); let url = format!("postgres://lfs:{SECRET}@localhost:5432/layerfs?sslmode=verify-full"); let rewriting: &[Platform] = match cfg!(target_os = "linux") { - true => &[Platform::Lima], + true => &[Platform::Native, Platform::Docker, Platform::Lima], false => &[Platform::Docker, Platform::Lima], }; for &kind in rewriting { @@ -163,11 +168,27 @@ fn a_rewrite_is_refused_for_verify_full() { assert_eq!(code, Code::Unsupported); assert!(message.contains("sslmode=verify-full"), "{message}"); } - // native rewrites nothing, so its certificate check still holds - assert_eq!( - machine::reach(&spec(&scratch, Platform::Native), &url), - Ok(url.clone()) - ); + if !cfg!(target_os = "linux") { + // macOS native rewrites nothing, so its certificate check still holds + assert_eq!( + machine::reach(&spec(&scratch, Platform::Native), &url), + Ok(url.clone()) + ); + } else { + // Linux native and docker keep 127.0.0.1 and [::1] unchanged even with verify-full + for kind in [Platform::Native, Platform::Docker] { + for literal in [ + format!("postgres://lfs:{SECRET}@127.0.0.1:5432/layerfs?sslmode=verify-full"), + format!("postgres://lfs:{SECRET}@[::1]:5432/layerfs?sslmode=verify-full"), + ] { + assert_eq!( + machine::reach(&spec(&scratch, kind), &literal), + Ok(literal), + "{kind:?}" + ); + } + } + } // verify-ca does not check the host name let ca = url.replace("verify-full", "verify-ca"); assert_eq!( diff --git a/control/crates/layerfs-sandbox/src/launch/local.rs b/control/crates/layerfs-sandbox/src/launch/local.rs index c02e234ae0..759548d707 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,31 @@ 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.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/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs b/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs new file mode 100644 index 0000000000..3976718e03 --- /dev/null +++ b/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs @@ -0,0 +1,96 @@ +//! Sandbox route URL rewriting on Linux (`docker` and `native`): +//! `localhost` becomes `127.0.0.1` so daemons in a rootfs without `/etc/hosts` +//! can dial it, while `::1`, `127.0.0.1`, and `sslmode=verify-full` rules stay +//! intact. +#![cfg(all(feature = "machine", target_os = "linux"))] + +use layerfs_bridge::control::SdkValue; +use layerfs_home::home::{self, paths, secrets, write_entity}; +use layerfs_store::record::StoreRecord; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::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-sb-reach-{tag}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +fn write_store(home: &std::path::Path, url: &str) -> StoreRecord { + let value = SdkValue::map([ + ("v", SdkValue::Int(1)), + ("name", SdkValue::text("shop")), + ("kind", SdkValue::text("postgresql")), + ("url", SdkValue::text(url)), + ("auth", SdkValue::text("pg")), + ("binding", SdkValue::Bytes(vec![7; 16])), + ]); + write_entity(&paths::store_record(home, "shop"), &value).unwrap(); + StoreRecord::of(home, "shop").unwrap() +} + +#[test] +fn linux_docker_and_native_rewrite_localhost_to_127_0_0_1_and_keep_v6_and_verify_full() { + let home = tempdir("home"); + let opened = home::open(&home).unwrap(); + layerfs_machine::ensure_built_ins(&home, &opened.id).unwrap(); + secrets::save_secret( + &home, + "auth", + "pg", + &SdkValue::map([ + ("user", SdkValue::text("app")), + ("password", SdkValue::text(SECRET)), + ]), + ) + .unwrap(); + for machine in ["native", "docker"] { + let r = write_store(&home, "postgresql://localhost:55432/shop?sslmode=disable"); + let (sel, _) = layerfs_sandbox::route::reached(&home, machine, &r).unwrap(); + assert_eq!( + sel.url.as_deref(), + Some("postgresql://app:s3cr3t-pg-pw@127.0.0.1:55432/shop?sslmode=disable"), + "{machine}" + ); + + let v6 = write_store(&home, "postgresql://[::1]:55432/shop?sslmode=verify-full"); + let (sel_v6, _) = layerfs_sandbox::route::reached(&home, machine, &v6).unwrap(); + assert_eq!( + sel_v6.url.as_deref(), + Some("postgresql://app:s3cr3t-pg-pw@[::1]:55432/shop?sslmode=verify-full"), + "{machine}" + ); + + let v4 = write_store( + &home, + "postgresql://127.0.0.1:55432/shop?sslmode=verify-full", + ); + let (sel_v4, _) = layerfs_sandbox::route::reached(&home, machine, &v4).unwrap(); + assert_eq!( + sel_v4.url.as_deref(), + Some("postgresql://app:s3cr3t-pg-pw@127.0.0.1:55432/shop?sslmode=verify-full"), + "{machine}" + ); + + let verify_localhost = write_store( + &home, + "postgresql://localhost:55432/shop?sslmode=verify-full", + ); + let Err(err) = layerfs_sandbox::route::reached(&home, machine, &verify_localhost) else { + panic!("{machine}: expected Unsupported for localhost with verify-full"); + }; + assert_eq!(err.code, "Unsupported", "{machine}: {err:?}"); + assert!(!err.message.contains(SECRET), "{err:?}"); + } + let _ = std::fs::remove_dir_all(&home); +} 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/control/machines/platforms.md b/docs/architecture/control/machines/platforms.md index f81fcadf8b..3338da124a 100644 --- a/docs/architecture/control/machines/platforms.md +++ b/docs/architecture/control/machines/platforms.md @@ -53,7 +53,7 @@ Linux, Store calls run in the caller's process and there is no worker. | `stop` | nothing to stop | | `status` | `running`; `down_reason` "missing: …" when the host lacks something | | `guest`, `copy_in`, `copy_out` | `InvalidInput`: "runs in-process; its files are the host's" | -| `reach` | the URL as given (`Loopback::Shared`) | +| `reach` | `Loopback::Shared`: unchanged on macOS; on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged) | | `forward` | `127.0.0.1:`, no pid | ## docker (`platforms/docker/`) diff --git a/docs/architecture/control/machines/workers-and-reach.md b/docs/architecture/control/machines/workers-and-reach.md index 249215acce..f211e486c8 100644 --- a/docs/architecture/control/machines/workers-and-reach.md +++ b/docs/architecture/control/machines/workers-and-reach.md @@ -268,7 +268,11 @@ nothing, and no message holds any part of the URL. ```text dial(spec, url, loopback) - Shared? ------------------------------------------> url as given + Shared (non-Linux)? ------------------------------> url as given + Shared (Linux)? ---> host == localhost? + no ------------------------> url as given + yes, verify-full ----------> Unsupported + yes -----------------------> with_host(127.0.0.1) one postgres[ql]://[user@]host[:port]/... ? no --> InvalidInput ?host= or ?hostaddr= ------------------------ yes --> Unsupported no host (a Unix socket) --------------------- yes --> Unsupported @@ -279,8 +283,8 @@ nothing, and no message holds any part of the URL. | Platform | `Loopback` | A loopback host becomes | | --- | --- | --- | -| `native` | `Shared` | unchanged; the URL is not parsed | -| `docker` | `Shared` on a Linux host; `Lookup` on Docker Desktop | the address the running worker resolves `host.docker.internal` to | +| `native` | `Shared` | unchanged on macOS; on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged) | +| `docker` | `Shared` on a Linux host; `Lookup` on Docker Desktop | on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged); on Docker Desktop the address the running worker resolves `host.docker.internal` to | | `lima` | `Alias` | `192.168.5.2` | | `apple-container` | `Alias` (recorded gateway), else `Lookup` | the gateway the last start recorded, else `container inspect`'s while running; a stale recorded gateway is dialled as recorded | 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}"); +} From 9cf5b0b1112ab7fb104689b0f0e717ec99ca530f Mon Sep 17 00:00:00 2001 From: liuyuchen <152110621+jiangkoumo@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:06:20 +0000 Subject: [PATCH 2/3] Keep localhost Dual-Stack Loopback in PostgreSQL Connector Revert the Loopback::Shared localhost-to-127.0.0.1 rewrite in layerfs-platform/src/reach.rs (and its reachability/conformance test changes) so localhost URLs remain intact across native host checks, store doctor, and Sandbox routes, restoring IPv6 ::1-only localhost PostgreSQL connectivity. In engine/crates/layerfs-persistence (Connector::new), pair a single localhost TCP host (when no hostaddr is explicitly configured) with both 127.0.0.1 and ::1 via Config::hostaddr while retaining localhost for TLS hostname verification (sslmode=verify-full), so Sandbox roots without /etc/hosts or DNS dial both IPv4 and IPv6 loopback directly. Narrow the /etc/hosts hint in control/crates/layerfs-sandbox/src/launch/local.rs to exclude localhost, and update docs/architecture/engine/store/postgresql.md. Deleted tests: - control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs (tested the reverted route::reached localhost -> 127.0.0.1 rewrite) Production LOC (tools/production_loc.py --root): - From 5276f5c33: core +0 (40988->40988), engine +12 (95889->95901), control -13 (58807->58794), api +0 (10266->10266), total -1 (205950->205949) - From ed9118963: core +0 (40988->40988), engine +56 (95845->95901), control +49 (58745->58794), api +0 (10266->10266), total +105 (205844->205949) --- .../src/platforms/docker/adapter.rs | 9 +- control/crates/layerfs-platform/src/reach.rs | 36 ++----- .../layerfs-platform/tests/conformance.rs | 16 +--- .../layerfs-platform/tests/machine_reach.rs | 33 ++----- .../layerfs-sandbox/src/launch/local.rs | 5 +- .../tests/postgres_reach_localhost.rs | 96 ------------------- .../control/machines/platforms.md | 2 +- .../control/machines/workers-and-reach.md | 10 +- docs/architecture/engine/store/postgresql.md | 5 +- .../backend/postgresql/session/connection.rs | 16 +++- 10 files changed, 48 insertions(+), 180 deletions(-) delete mode 100644 control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs diff --git a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs index 1a9a3f760c..03f8b44d35 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs @@ -82,10 +82,11 @@ impl Adapter for Docker { status(spec) } /// On a Linux Engine the worker shares the host's network, and its - /// `namespaces` Sandboxes share the worker's (D-8), though their image - /// root has no `/etc/hosts` so `localhost` becomes `127.0.0.1`. Elsewhere - /// (Docker Desktop) a loopback URL becomes the address the running worker - /// container resolves `host.docker.internal` to. + /// `namespaces` Sandboxes share the worker's (D-8), so a loopback URL is + /// dialled as given. Elsewhere (Docker Desktop) a loopback URL becomes + /// the address the running worker container resolves + /// `host.docker.internal` to: a Sandbox image's root cannot resolve + /// the name. fn reach(&self, spec: &Spec, url: &str) -> Result { if cfg!(target_os = "linux") { return dial(spec, url, Loopback::Shared); diff --git a/control/crates/layerfs-platform/src/reach.rs b/control/crates/layerfs-platform/src/reach.rs index 2926aff786..11a5968aaf 100644 --- a/control/crates/layerfs-platform/src/reach.rs +++ b/control/crates/layerfs-platform/src/reach.rs @@ -24,27 +24,19 @@ pub(crate) enum Loopback<'a> { /// The URL `spec`'s daemon dials for `url`, given how its machine reaches /// the caller's loopback. pub(crate) fn dial(spec: &Spec, url: &str, loopback: Loopback<'_>) -> Result { - let shared_linux = matches!(loopback, Loopback::Shared) && cfg!(target_os = "linux"); - if matches!(loopback, Loopback::Shared) && !shared_linux { + if let Loopback::Shared = loopback { return Ok(url.to_owned()); } // a host list (`h1:5432,h2:5433`) reads as one host holding a `,` let parsed = PostgresUrl::parse(url).filter(|p| !p.host().contains(',')); - let parsed = match parsed { - Some(parsed) => parsed, - None if shared_linux => return Ok(url.to_owned()), - None => { - return Err(refuse( - spec, - Code::InvalidInput, - "its URL is not one postgres://[user@]host[:port]/... URL with one host", - )); - } - }; + let parsed = parsed.ok_or_else(|| { + refuse( + spec, + Code::InvalidInput, + "its URL is not one postgres://[user@]host[:port]/... URL with one host", + ) + })?; if parsed.query("host").chain(parsed.query("hostaddr")).count() > 0 { - if shared_linux { - return Ok(url.to_owned()); - } return Err(refuse( spec, Code::Unsupported, @@ -52,21 +44,13 @@ pub(crate) fn dial(spec: &Spec, url: &str, loopback: Loopback<'_>) -> Result) -> Result "127.0.0.1".to_owned(), Loopback::Alias(alias) => alias.to_owned(), Loopback::Lookup(read) => read()?, + Loopback::Shared => unreachable!("answered above"), }; Ok(parsed.with_host(&alias)) } diff --git a/control/crates/layerfs-platform/tests/conformance.rs b/control/crates/layerfs-platform/tests/conformance.rs index c8a094d50d..64b80ec9c6 100644 --- a/control/crates/layerfs-platform/tests/conformance.rs +++ b/control/crates/layerfs-platform/tests/conformance.rs @@ -426,11 +426,6 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { for (i, url) in loopback_urls(query).iter().enumerate() { let outcome = machine::reach(&spec, url); match loopback(&spec) { - Loopback::Shared if cfg!(target_os = "linux") && i == 1 => assert_eq!( - outcome, - Ok(with_host("127.0.0.1", query)[1].clone()), - "{platform:?}" - ), Loopback::Shared => assert_eq!(outcome.as_ref(), Ok(url)), Loopback::Alias(alias) => assert_eq!( outcome, @@ -441,18 +436,9 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { } } // the server's certificate names the loopback host, not an alias - for (i, url) in loopback_urls("?sslmode=verify-full") - .into_iter() - .enumerate() - { + for url in loopback_urls("?sslmode=verify-full") { let outcome = machine::reach(&spec, &url); match loopback(&spec) { - Loopback::Shared if cfg!(target_os = "linux") && i == 1 => { - let (code, message) = refused(platform, outcome); - assert_eq!(code, Code::Unsupported, "{message}"); - assert!(message.starts_with(&prefix), "{message}"); - assert!(message.contains("sslmode=verify-full"), "{message}"); - } Loopback::Shared => assert_eq!(outcome, Ok(url)), Loopback::Alias(_) => { let (code, message) = refused(platform, outcome); diff --git a/control/crates/layerfs-platform/tests/machine_reach.rs b/control/crates/layerfs-platform/tests/machine_reach.rs index a89d4d448f..f0fb37e49f 100644 --- a/control/crates/layerfs-platform/tests/machine_reach.rs +++ b/control/crates/layerfs-platform/tests/machine_reach.rs @@ -74,11 +74,6 @@ fn each_platform_rewrites_a_loopback_host() { for (i, url) in loopback_urls().iter().enumerate() { let outcome = machine::reach(&spec, url); match alias { - // Linux namespaces Sandboxes have no /etc/hosts, so localhost - // becomes 127.0.0.1 while 127.0.0.1 and [::1] stay unchanged. - "unchanged" if cfg!(target_os = "linux") && i == 1 => { - assert_eq!(outcome, Ok(rewritten("127.0.0.1")[1].clone()), "{kind:?}") - } "unchanged" => assert_eq!(outcome.as_deref(), Ok(url.as_str())), alias => assert_eq!(outcome, Ok(rewritten(alias)[i].clone()), "{kind:?}"), } @@ -160,7 +155,7 @@ fn a_rewrite_is_refused_for_verify_full() { let scratch = Scratch::new("reach-tls"); let url = format!("postgres://lfs:{SECRET}@localhost:5432/layerfs?sslmode=verify-full"); let rewriting: &[Platform] = match cfg!(target_os = "linux") { - true => &[Platform::Native, Platform::Docker, Platform::Lima], + true => &[Platform::Lima], false => &[Platform::Docker, Platform::Lima], }; for &kind in rewriting { @@ -168,27 +163,11 @@ fn a_rewrite_is_refused_for_verify_full() { assert_eq!(code, Code::Unsupported); assert!(message.contains("sslmode=verify-full"), "{message}"); } - if !cfg!(target_os = "linux") { - // macOS native rewrites nothing, so its certificate check still holds - assert_eq!( - machine::reach(&spec(&scratch, Platform::Native), &url), - Ok(url.clone()) - ); - } else { - // Linux native and docker keep 127.0.0.1 and [::1] unchanged even with verify-full - for kind in [Platform::Native, Platform::Docker] { - for literal in [ - format!("postgres://lfs:{SECRET}@127.0.0.1:5432/layerfs?sslmode=verify-full"), - format!("postgres://lfs:{SECRET}@[::1]:5432/layerfs?sslmode=verify-full"), - ] { - assert_eq!( - machine::reach(&spec(&scratch, kind), &literal), - Ok(literal), - "{kind:?}" - ); - } - } - } + // native rewrites nothing, so its certificate check still holds + assert_eq!( + machine::reach(&spec(&scratch, Platform::Native), &url), + Ok(url.clone()) + ); // verify-ca does not check the host name let ca = url.replace("verify-full", "verify-ca"); assert_eq!( diff --git a/control/crates/layerfs-sandbox/src/launch/local.rs b/control/crates/layerfs-sandbox/src/launch/local.rs index 759548d707..9a0f55ac51 100644 --- a/control/crates/layerfs-sandbox/src/launch/local.rs +++ b/control/crates/layerfs-sandbox/src/launch/local.rs @@ -492,7 +492,10 @@ fn abandon( format!( "Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server" ) - } else if namespaces && pg_host.parse::().is_err() { + } 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)" ) diff --git a/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs b/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs deleted file mode 100644 index 3976718e03..0000000000 --- a/control/crates/layerfs-sandbox/tests/postgres_reach_localhost.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Sandbox route URL rewriting on Linux (`docker` and `native`): -//! `localhost` becomes `127.0.0.1` so daemons in a rootfs without `/etc/hosts` -//! can dial it, while `::1`, `127.0.0.1`, and `sslmode=verify-full` rules stay -//! intact. -#![cfg(all(feature = "machine", target_os = "linux"))] - -use layerfs_bridge::control::SdkValue; -use layerfs_home::home::{self, paths, secrets, write_entity}; -use layerfs_store::record::StoreRecord; -use std::os::unix::fs::PermissionsExt; -use std::path::PathBuf; -use std::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-sb-reach-{tag}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); - dir -} - -fn write_store(home: &std::path::Path, url: &str) -> StoreRecord { - let value = SdkValue::map([ - ("v", SdkValue::Int(1)), - ("name", SdkValue::text("shop")), - ("kind", SdkValue::text("postgresql")), - ("url", SdkValue::text(url)), - ("auth", SdkValue::text("pg")), - ("binding", SdkValue::Bytes(vec![7; 16])), - ]); - write_entity(&paths::store_record(home, "shop"), &value).unwrap(); - StoreRecord::of(home, "shop").unwrap() -} - -#[test] -fn linux_docker_and_native_rewrite_localhost_to_127_0_0_1_and_keep_v6_and_verify_full() { - let home = tempdir("home"); - let opened = home::open(&home).unwrap(); - layerfs_machine::ensure_built_ins(&home, &opened.id).unwrap(); - secrets::save_secret( - &home, - "auth", - "pg", - &SdkValue::map([ - ("user", SdkValue::text("app")), - ("password", SdkValue::text(SECRET)), - ]), - ) - .unwrap(); - for machine in ["native", "docker"] { - let r = write_store(&home, "postgresql://localhost:55432/shop?sslmode=disable"); - let (sel, _) = layerfs_sandbox::route::reached(&home, machine, &r).unwrap(); - assert_eq!( - sel.url.as_deref(), - Some("postgresql://app:s3cr3t-pg-pw@127.0.0.1:55432/shop?sslmode=disable"), - "{machine}" - ); - - let v6 = write_store(&home, "postgresql://[::1]:55432/shop?sslmode=verify-full"); - let (sel_v6, _) = layerfs_sandbox::route::reached(&home, machine, &v6).unwrap(); - assert_eq!( - sel_v6.url.as_deref(), - Some("postgresql://app:s3cr3t-pg-pw@[::1]:55432/shop?sslmode=verify-full"), - "{machine}" - ); - - let v4 = write_store( - &home, - "postgresql://127.0.0.1:55432/shop?sslmode=verify-full", - ); - let (sel_v4, _) = layerfs_sandbox::route::reached(&home, machine, &v4).unwrap(); - assert_eq!( - sel_v4.url.as_deref(), - Some("postgresql://app:s3cr3t-pg-pw@127.0.0.1:55432/shop?sslmode=verify-full"), - "{machine}" - ); - - let verify_localhost = write_store( - &home, - "postgresql://localhost:55432/shop?sslmode=verify-full", - ); - let Err(err) = layerfs_sandbox::route::reached(&home, machine, &verify_localhost) else { - panic!("{machine}: expected Unsupported for localhost with verify-full"); - }; - assert_eq!(err.code, "Unsupported", "{machine}: {err:?}"); - assert!(!err.message.contains(SECRET), "{err:?}"); - } - let _ = std::fs::remove_dir_all(&home); -} diff --git a/docs/architecture/control/machines/platforms.md b/docs/architecture/control/machines/platforms.md index 3338da124a..f81fcadf8b 100644 --- a/docs/architecture/control/machines/platforms.md +++ b/docs/architecture/control/machines/platforms.md @@ -53,7 +53,7 @@ Linux, Store calls run in the caller's process and there is no worker. | `stop` | nothing to stop | | `status` | `running`; `down_reason` "missing: …" when the host lacks something | | `guest`, `copy_in`, `copy_out` | `InvalidInput`: "runs in-process; its files are the host's" | -| `reach` | `Loopback::Shared`: unchanged on macOS; on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged) | +| `reach` | the URL as given (`Loopback::Shared`) | | `forward` | `127.0.0.1:`, no pid | ## docker (`platforms/docker/`) diff --git a/docs/architecture/control/machines/workers-and-reach.md b/docs/architecture/control/machines/workers-and-reach.md index f211e486c8..249215acce 100644 --- a/docs/architecture/control/machines/workers-and-reach.md +++ b/docs/architecture/control/machines/workers-and-reach.md @@ -268,11 +268,7 @@ nothing, and no message holds any part of the URL. ```text dial(spec, url, loopback) - Shared (non-Linux)? ------------------------------> url as given - Shared (Linux)? ---> host == localhost? - no ------------------------> url as given - yes, verify-full ----------> Unsupported - yes -----------------------> with_host(127.0.0.1) + Shared? ------------------------------------------> url as given one postgres[ql]://[user@]host[:port]/... ? no --> InvalidInput ?host= or ?hostaddr= ------------------------ yes --> Unsupported no host (a Unix socket) --------------------- yes --> Unsupported @@ -283,8 +279,8 @@ nothing, and no message holds any part of the URL. | Platform | `Loopback` | A loopback host becomes | | --- | --- | --- | -| `native` | `Shared` | unchanged on macOS; on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged) | -| `docker` | `Shared` on a Linux host; `Lookup` on Docker Desktop | on Linux `localhost` becomes `127.0.0.1` (`127.0.0.1` and `::1` stay unchanged); on Docker Desktop the address the running worker resolves `host.docker.internal` to | +| `native` | `Shared` | unchanged; the URL is not parsed | +| `docker` | `Shared` on a Linux host; `Lookup` on Docker Desktop | the address the running worker resolves `host.docker.internal` to | | `lima` | `Alias` | `192.168.5.2` | | `apple-container` | `Alias` (recorded gateway), else `Lookup` | the gateway the last start recorded, else `container inspect`'s while running; a stale recorded gateway is dialled as recorded | 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-persistence/src/backend/postgresql/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs index c9343a2235..6f1b2081b0 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()?), From ffd7e77d852c2e14294632577661197f47f2d569 Mon Sep 17 00:00:00 2001 From: liuyuchen <152110621+jiangkoumo@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:49:31 +0000 Subject: [PATCH 3/3] test(pg-localhost): acceptance tests for localhost dual-stack loopback postgresql_localhost (layerfs-persistence, real PostgreSQL, env-gated): a localhost URL reaches a server listening only on ::1 or only on 127.0.0.1, also where localhost does not resolve; IP literals and a given hostaddr are dialled as given; other host names and Unix sockets get no loopback; sslmode=verify-full is refused as before; TLS checks the name localhost. localhost_reach (layerfs-platform): Linux native and docker dial every Store URL as the caller and store doctor dial it. No tests deleted. Production LOC: 205,949 -> 205,949 (delta 0) core 40,988 -> 40,988 (0) engine 95,901 -> 95,901 (0) control 58,794 -> 58,794 (0) api 10,266 -> 10,266 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 9cf5b0b11 and the staged tree Co-Authored-By: Claude Opus 5.5 --- .../layerfs-platform/tests/localhost_reach.rs | 48 ++++++ .../tests/postgresql_localhost.rs | 159 ++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 control/crates/layerfs-platform/tests/localhost_reach.rs create mode 100644 engine/crates/layerfs-persistence/tests/postgresql_localhost.rs 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/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 + ); +}