diff --git a/api/crates/layerfs-api/tests/sandbox_machines.rs b/api/crates/layerfs-api/tests/sandbox_machines.rs index 55a69d0f91..aa2de7c36e 100644 --- a/api/crates/layerfs-api/tests/sandbox_machines.rs +++ b/api/crates/layerfs-api/tests/sandbox_machines.rs @@ -10,8 +10,11 @@ //! LAYERFS_TEST_PG_PASSWORD, LAYERFS_TEST_DAEMON (a host daemon built with //! `postgresql`); the docker half also LAYERFS_TEST_IMAGE (a local image //! digest, the worker container's) and LAYERFS_BUNDLE (a sealed Linux -//! bundle whose daemon has `postgresql`). macOS reaches a loopback server -//! from the container as `host.docker.internal`. +//! bundle whose daemon has `postgresql`). The URL is never rewritten: on +//! Docker Desktop a loopback URL is refused for the docker machine, which +//! is then given its own URL naming `host.docker.internal`, which its +//! Sandboxes resolve with the worker's resolver files; their Workspace +//! and Commit never show those files. //! - a sqlite Store pushed to the docker machine and its Sandbox, through the //! docker worker: LAYERFS_TEST_IMAGE and LAYERFS_BUNDLE. The Sandbox runs //! in namespaces inside the privileged worker container and shows @@ -79,6 +82,26 @@ fn pg_record(home: &Path) { .unwrap(); } +/// Sandbox `s1` of project `pg/app`, started on machine `machine`, as its +/// record keeps it (nothing runs). +fn sandbox_on(home: &Path, machine: &str) { + home::write_record( + &paths::sandbox_record(home, "s1"), + &SdkValue::map([ + ("v", SdkValue::Int(1)), + ("name", t("s1")), + ("project", t("pg/app")), + ("machine", t(machine)), + ("created", SdkValue::Int(1)), + ("id", t("s1")), + ("platform", t("lima")), + ("runtime", t("namespaces")), + ("backend", t("namespaces")), + ]), + ) + .unwrap(); +} + fn env(name: &str) -> Option { std::env::var(name).ok().filter(|v| !v.is_empty()) } @@ -202,8 +225,39 @@ fn a_sandbox_runs_where_its_store_can_be_reached() { layerfs_platform::StoreKind::Postgresql, ) { Ok(()) => { + // a loopback URL is refused before the machine is asked: lima + // does not share this host's loopback, and nothing rewrites it + assert_eq!(code, "Unsupported", "{message}"); + assert!(message.contains("host.lima.internal"), "{message}"); + assert!( + message.contains("`layerfs store connect pg --machine dev`"), + "{message}" + ); + // a Sandbox already on the machine is still read and removed: + // the calls that never dial the Store's URL are not refused for + // it, and reach the machine (here stopped) instead + sandbox_on(&home, "dev"); + ok(&home, "sandbox.get", &[("sandbox", t("s1"))]); + let (code, message) = + call(&home, "sandbox.remove", &[("sandbox", t("s1"))]).unwrap_err(); + assert!(!message.contains("loopback"), "{code}: {message}"); + assert!(message.contains("layerfs machine start dev"), "{message}"); + std::fs::remove_dir_all(paths::sandbox_dir(&home, "s1")).unwrap(); + // any other host: the stopped machine is refused naming its start + let record = paths::store_record(&home, "pg"); + let mut fields = home::read_record(&record).unwrap().unwrap(); + if let SdkValue::Map(entries) = &mut fields { + for (name, value) in entries.iter_mut() { + if name == "url" { + *value = t("postgres://db.invalid:1/db"); + } + } + } + home::write_record(&record, &fields).unwrap(); + let (code, message) = create("dev"); assert_eq!(code, "Unavailable", "{message}"); assert!(message.contains("layerfs machine start dev"), "{message}"); + pg_record(&home); } Err(reason) => { assert_eq!(code, "Unsupported", "{message}"); @@ -390,22 +444,47 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { ok( &home, "machine.update", - &[("name", t("docker")), ("image", t(&image))], + &[("machine", t("docker")), ("image", t(&image))], ); let outcome = std::panic::catch_unwind(|| { // only `machine.start` starts a machine (D11) - ok(&home, "machine.start", &[("name", t("docker"))]); - // docker runs the Store's Sandboxes with no step before the - // create, whose reach check dials from the worker container - ok( - &home, - "sandbox.create", - &[ - ("project", t("pg/app")), - ("name", t("d")), - ("machine", t("docker")), - ], - ); + ok(&home, "machine.start", &[("machine", t("docker"))]); + let create = || { + call( + &home, + "sandbox.create", + &[ + ("project", t("pg/app")), + ("name", t("d")), + ("machine", t("docker")), + ], + ) + }; + // Docker Desktop's worker does not share this host's loopback: + // a loopback URL is refused, naming the host's name there, and + // the machine gets its own URL (nothing is rewritten) + let loopback = ["127.0.0.1", "localhost", "[::1]"] + .iter() + .find(|host| address.starts_with(*host)); + if let (Some(host), false) = (loopback, cfg!(target_os = "linux")) { + let (code, message) = create().unwrap_err(); + assert_eq!(code, "Unsupported", "{message}"); + assert!(message.contains("host.docker.internal"), "{message}"); + assert!(message.contains("--machine docker"), "{message}"); + let own = address.replacen(host, "host.docker.internal", 1); + ok( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&format!("{scheme}://{own}"))), + ("machine", t("docker")), + ], + ); + } + // the create's reach check dials from the worker container + create().unwrap(); + resolves_as_the_worker(&home, "pg/app", "d"); work(&home, "pg/app", "d", "on-docker", "docker.txt"); ok(&home, "sandbox.remove", &[("sandbox", t("d"))]); }); @@ -435,6 +514,61 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { std::fs::remove_dir_all(&folder).unwrap(); } +/// A Sandbox resolves names as its machine's worker does: the worker's +/// `/etc/resolv.conf` and `/etc/hosts` are bound over its root's, so +/// `host.docker.internal` resolves in it on Docker Desktop. Reading them +/// changes nothing a Workspace shows: no change, an UpToDate Commit, and +/// neither file in the Workspace's tree. +fn resolves_as_the_worker(home: &Path, project: &str, sandbox: &str) { + ok( + home, + "branch.fork", + &[ + ("project", t(project)), + ("name", t("resolver")), + ("from", t("main")), + ], + ); + let mounted = ok( + home, + "workspace.mount", + &[("sandbox", t(sandbox)), ("branch", t("resolver"))], + ); + let ws = mounted.get_text("workspace").unwrap().to_owned(); + let name = if cfg!(target_os = "linux") { + "localhost" + } else { + "host.docker.internal" + }; + let ran = ok( + home, + "workspace.exec", + &[ + ("workspace", t(&ws)), + ( + "command", + t(&format!( + "test -s /etc/resolv.conf && test -s /etc/hosts && getent hosts {name} && ls -a" + )), + ), + ], + ); + assert_eq!(ran.get_int("exit_code"), Some(0), "{ran:?}"); + let listed = ran.get_text("stdout").unwrap_or_default().to_owned(); + for line in listed.lines() { + assert!(!matches!(line, "etc" | "resolv.conf" | "hosts"), "{listed}"); + } + let status = ok(home, "workspace.status", &[("workspace", t(&ws))]); + assert_eq!( + status.get("changes"), + Some(&SdkValue::List(Vec::new())), + "{status:?}" + ); + let committed = ok(home, "workspace.commit", &[("workspace", t(&ws))]); + assert!(committed.get("unchanged").is_some(), "{committed:?}"); + ok(home, "workspace.unmount", &[("workspace", t(&ws))]); +} + /// Removes the docker worker container and data volume of the home `id`, /// whatever its test did. fn remove_worker(id: &str) { @@ -473,7 +607,7 @@ fn a_sqlite_store_s_sandbox_on_the_docker_machine() { ok( &home, "machine.update", - &[("name", t("docker")), ("image", t(&image))], + &[("machine", t("docker")), ("image", t(&image))], ); ok(&home, "store.create", &[("name", t("shop"))]); ok( @@ -486,7 +620,7 @@ fn a_sqlite_store_s_sandbox_on_the_docker_machine() { ); let outcome = std::panic::catch_unwind(|| { // only `machine.start` starts a machine (D11) - ok(&home, "machine.start", &[("name", t("docker"))]); + ok(&home, "machine.start", &[("machine", t("docker"))]); let moved = ok( &home, "store.move", @@ -537,7 +671,12 @@ fn a_sqlite_store_s_sandbox_on_each_running_vm_machine() { }; let home = PathBuf::from(home); for machine in machines.split(',') { - let status = ok(&home, "machine.status", &[("name", t(machine))]); + let live = SdkValue::List(vec![t("live")]); + let status = ok( + &home, + "machine.get", + &[("machine", t(machine)), ("with", live)], + ); assert_eq!( status.get_text("state"), Some("running"), diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index 9739745bdd..9e21ca6fad 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -247,10 +247,10 @@ fn runs_postgresql_sandboxes(home: &Path, store: &str, machine: &str) -> Result< } /// `refusal` of the check from machine `machine`, naming it, the Store and -/// the host it dialled (never the URL), with the platform's `hint` when -/// the server was not reached (a server that answered with another Store -/// was reached). A worker from a bundle without the check says how to -/// update it. +/// the host it dialled (never the URL), with the platform's `hint` only +/// when no connection was made (a server that answered, with a refused +/// login or another Store, was reached). A worker from a bundle without +/// the check says how to update it. fn from_machine( refusal: SdkRefusal, (store, machine, host): (&str, &str, &str), @@ -265,7 +265,10 @@ fn from_machine( ), ), "Unavailable" if !message.starts_with(check::ANOTHER_STORE) => { - let hint = hint.map(|hint| format!("; {hint}")).unwrap_or_default(); + let hint = hint + .filter(|_| layerfs_store::postgresql::open::not_connected(&message)) + .map(|hint| format!("; {hint}")) + .unwrap_or_default(); refused( "Unavailable", format!( @@ -328,7 +331,8 @@ pub(crate) fn check_from( } } }; - let checked = checked.map_err(|refusal| from_machine(refusal, (name, machine, &host), hint)); + let checked = + checked.map_err(|refusal| from_machine(refusal, (name, machine, &host), hint.as_deref())); (Some(host), checked) } diff --git a/control/crates/layerfs-platform/src/adapter.rs b/control/crates/layerfs-platform/src/adapter.rs index 8ab6b167c6..511882a13d 100644 --- a/control/crates/layerfs-platform/src/adapter.rs +++ b/control/crates/layerfs-platform/src/adapter.rs @@ -37,10 +37,10 @@ pub(crate) trait Adapter: Sync { fn provider_state(&self, spec: &Spec) -> Result; /// The machine's state now; starts nothing. fn status(&self, spec: &Spec) -> Result; - /// The PostgreSQL Store URL the machine's Sandbox daemons dial for - /// `url`: a loopback host becomes the machine's host alias, or is - /// refused naming what is missing (`crate::reach`). Starts nothing. - fn reach(&self, spec: &Spec, url: &str) -> Result; + /// How the machine's Sandboxes reach the caller's loopback, which + /// `crate::reach` checks every PostgreSQL Store URL against. Reads + /// nothing from the machine. + fn loopback(&self, spec: &Spec) -> crate::reach::Loopback; /// The host loopback address at which this process reaches a Sandbox /// daemon listening on `127.0.0.1:` in the machine (the /// worker's network namespace), or why the machine forwards none diff --git a/control/crates/layerfs-platform/src/lib.rs b/control/crates/layerfs-platform/src/lib.rs index 135f109cf3..df4beeb0fe 100644 --- a/control/crates/layerfs-platform/src/lib.rs +++ b/control/crates/layerfs-platform/src/lib.rs @@ -37,8 +37,8 @@ pub use probe::{native_missing, probe, Probe}; pub use setup::find_tool; pub use setup::{ cached_image, copy_in, copy_out, create, data_volume, forward, forward_close, load_image, - name_limit, provider_within, reach, remove, start, status, status_within, stop, stop_force, - worker_port, State, Status, + loopback_hint, name_limit, provider_within, reach, remove, start, status, status_within, stop, + stop_force, worker_port, State, Status, }; pub use spec::{ parse_size, search_path, tool_fallbacks, Bundle, Endpoint, Forward, Lasting, NameLimit, diff --git a/control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs b/control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs index b5a6324aa3..a24547aa8d 100644 --- a/control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs @@ -1,11 +1,10 @@ //! `apple-container`'s adapter. -use super::observe::gateway; use super::{create, guest, remove, start, status, stop}; use crate::adapter::Adapter; use crate::error::{Code, MachineError}; use crate::platform::HostOs; use crate::probe::{macos_missing, tool_version}; -use crate::reach::{dial, Loopback}; +use crate::reach::Loopback; use crate::setup::forward::refuse; use crate::setup::guest::Guest; use crate::setup::Status; @@ -54,16 +53,19 @@ impl Adapter for AppleContainer { fn status(&self, spec: &Spec) -> Result { status(spec) } - /// A loopback URL becomes the container network's gateway (G7 receipt): - /// the one its last start recorded (#66), else read from the machine - /// (a record from before #66, or a start that could not read it). A - /// recorded gateway that went stale is dialled as recorded and fails - /// there, explicitly; nothing looks it up again. - fn reach(&self, spec: &Spec, url: &str) -> Result { - match spec.state.gateway { - Some(recorded) => dial(spec, url, Loopback::Alias(&recorded.to_string())), - None => dial(spec, url, Loopback::Lookup(&|| gateway(spec))), - } + /// The guest has no name for this host: it reaches it at the container + /// network's gateway (G7 receipt), the one its last start recorded + /// (#66) when there is one, on which the server must listen (0.0.0.0, + /// as Docker Desktop publishes a port), not on 127.0.0.1 alone. + fn loopback(&self, spec: &Spec) -> Loopback { + let gateway = match spec.state.gateway { + Some(recorded) => recorded.to_string(), + None => "the container network's gateway, 192.168.64.1 on vmnet's default network" + .to_owned(), + }; + Loopback::Apart(format!( + "{gateway}, on which the server must listen, not on 127.0.0.1 alone; the machine has no name for this host" + )) } fn forward(&self, spec: &Spec, _guest_port: u16) -> Result { Err(refuse(spec, Code::Unsupported, FORWARD)) diff --git a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs index 03f8b44d35..9118d3b49a 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/adapter.rs @@ -1,12 +1,12 @@ //! `docker`'s adapter: the built-in machine on Docker's kernel, whose worker //! container runs `namespaces` Sandboxes (D-8). -use super::{guest, host_address, start, status, stop}; +use super::{guest, start, status, stop}; use crate::adapter::{refused, Adapter}; use crate::docker_socket::{socket_state, SocketState, SOCKET_ANSWER}; use crate::error::{Code, MachineError}; use crate::platform::{ExecutorKind, HostOs, Platform}; use crate::probe::first_line; -use crate::reach::{dial, Loopback}; +use crate::reach::Loopback; use crate::setup::forward::refuse; use crate::setup::guest::Guest; use crate::setup::{tool, Status}; @@ -17,6 +17,9 @@ use crate::spec::{Bundle, Forward, NameLimit, Running, Spec, Tools}; /// way Docker publishes one, so a later daemon's port cannot be (D-8). const FORWARD: &str = "Docker publishes a container's ports only when it starts, so a Sandbox daemon's port in the worker container cannot be published later; its Workspace calls go through the worker"; +/// The name Docker Desktop's DNS gives this host in its containers. +const DESKTOP_HOST: &str = "host.docker.internal"; + pub(crate) struct Docker; pub(crate) static ADAPTER: Docker = Docker; @@ -82,16 +85,15 @@ 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. - fn reach(&self, spec: &Spec, url: &str) -> Result { + /// `namespaces` Sandboxes share the worker's (D-8), so loopback is + /// shared. Docker Desktop's worker has a network of its own, which + /// calls this host `host.docker.internal` (Docker Desktop's DNS, which + /// the worker's Sandboxes use too). + fn loopback(&self, _spec: &Spec) -> Loopback { if cfg!(target_os = "linux") { - return dial(spec, url, Loopback::Shared); + return Loopback::Shared; } - dial(spec, url, Loopback::Lookup(&|| host_address(spec))) + Loopback::Apart(format!("{DESKTOP_HOST} names this host there")) } fn forward(&self, spec: &Spec, _guest_port: u16) -> Result { Err(refuse(spec, Code::Unsupported, FORWARD)) diff --git a/control/crates/layerfs-platform/src/platforms/docker/mod.rs b/control/crates/layerfs-platform/src/platforms/docker/mod.rs index e232c25644..1fe6945b27 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/mod.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/mod.rs @@ -24,8 +24,6 @@ pub(crate) use images::cached_image; pub(crate) use power::{load_image, start, stop}; pub(crate) use profile::PROFILE; #[cfg(any(target_os = "linux", target_os = "macos"))] -pub(crate) use unix::{guest, host_address, provider_state, status}; +pub(crate) use unix::{guest, provider_state, status}; #[cfg(not(any(target_os = "linux", target_os = "macos")))] -pub(crate) use windows::{ - cached_image, guest, host_address, load_image, provider_state, start, status, stop, -}; +pub(crate) use windows::{cached_image, guest, load_image, provider_state, start, status, stop}; diff --git a/control/crates/layerfs-platform/src/platforms/docker/unix.rs b/control/crates/layerfs-platform/src/platforms/docker/unix.rs index 881dfaba88..8af08d594a 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/unix.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/unix.rs @@ -13,10 +13,6 @@ use crate::spec::Spec; use std::time::Duration; const CALL: Duration = Duration::from_secs(30); -/// The name the worker container reaches the host's loopback by: Docker -/// Desktop's DNS answers it, and on a Linux Engine the worker's -/// `--add-host` entry. Its Sandboxes are given the address ([`host_address`]). -const DESKTOP_HOST: &str = "host.docker.internal"; pub(super) fn run(spec: &Spec, args: &[&str], what: &str) -> Result { tool::run(docker(spec, args)?, None, CALL, what) } @@ -45,30 +41,6 @@ pub(super) fn inspect(spec: &Spec) -> Result, MachineEr Ok(Some((state.to_owned(), role.to_owned()))) } -/// The IPv4 address the worker container resolves `host.docker.internal` -/// to (`getent ahostsv4`: Docker Desktop's DNS, or a Linux Engine's -/// `--add-host` entry). A Sandbox daemon runs in the Sandbox image's root, -/// which resolves neither, so it dials the address (D-8, as lima's). Read -/// from the running worker; refused `Unavailable` otherwise. -pub(crate) fn host_address(spec: &Spec) -> Result { - let out = run( - spec, - &["exec", &spec.vm_name, "getent", "ahostsv4", DESKTOP_HOST], - "resolving the worker's host address", - )?; - let first = out.stdout.split_whitespace().next(); - let found = first.filter(|text| out.ok() && text.parse::().is_ok()); - found.map(str::to_owned).ok_or_else(|| { - MachineError::new( - Code::Unavailable, - format!( - "the docker machine {}'s worker container resolves {DESKTOP_HOST} to no IPv4 address, so its Sandboxes cannot reach this host's loopback; it must be running", - spec.name - ), - ) - }) -} - /// The `layerfs.role` label of a machine's worker container. pub(super) const WORKER_ROLE: &str = "machine-worker"; diff --git a/control/crates/layerfs-platform/src/platforms/docker/windows.rs b/control/crates/layerfs-platform/src/platforms/docker/windows.rs index eb7bf93767..109549384e 100644 --- a/control/crates/layerfs-platform/src/platforms/docker/windows.rs +++ b/control/crates/layerfs-platform/src/platforms/docker/windows.rs @@ -35,10 +35,6 @@ pub(crate) fn load_image(spec: &Spec, _archive: &std::path::Path) -> Result Result { - Err(unsupported(spec)) -} - /// Provider observation on unsupported native Windows. pub(crate) fn provider_state(spec: &Spec) -> Result { status(spec).map(|value| value.state) diff --git a/control/crates/layerfs-platform/src/platforms/lima/adapter.rs b/control/crates/layerfs-platform/src/platforms/lima/adapter.rs index b6fcb129bd..b5a9a0707a 100644 --- a/control/crates/layerfs-platform/src/platforms/lima/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/lima/adapter.rs @@ -4,17 +4,16 @@ use crate::adapter::Adapter; use crate::error::MachineError; use crate::platform::HostOs; use crate::probe::{macos_missing, tool_version}; -use crate::reach::{dial, Loopback}; +use crate::reach::Loopback; use crate::setup::guest::Guest; use crate::setup::Status; use crate::spec::{Bundle, Forward, NameLimit, Running, Spec, Tools}; -/// The address a lima guest reaches the host's loopback at (#535 §7.3): the -/// gateway of Lima's default user-mode network, which the guest's -/// `/etc/hosts` names `host.lima.internal`. The address, not the name: a -/// Sandbox daemon runs in the Sandbox image's root, which has no such -/// hosts entry (G7 live receipt, `receipts/g7-live/`). -const HOST_ALIAS: &str = "192.168.5.2"; +/// What a lima guest calls this host (#535 §7.3): the guest's `/etc/hosts` +/// names `host.lima.internal`, the gateway of Lima's default user-mode +/// network (192.168.5.2, G7 live receipt). A Sandbox resolves it with its +/// machine's hosts file, bound into its root at start. +const HOST_NAME: &str = "host.lima.internal names this host there"; pub(crate) struct Lima; pub(crate) static ADAPTER: Lima = Lima; @@ -51,8 +50,8 @@ impl Adapter for Lima { fn status(&self, spec: &Spec) -> Result { status(spec) } - fn reach(&self, spec: &Spec, url: &str) -> Result { - dial(spec, url, Loopback::Alias(HOST_ALIAS)) + fn loopback(&self, _spec: &Spec) -> Loopback { + Loopback::Apart(HOST_NAME.to_owned()) } fn forward(&self, spec: &Spec, guest_port: u16) -> Result { daemon_forward(spec, guest_port) diff --git a/control/crates/layerfs-platform/src/platforms/native/adapter.rs b/control/crates/layerfs-platform/src/platforms/native/adapter.rs index fdaacea21e..7af2ac9010 100644 --- a/control/crates/layerfs-platform/src/platforms/native/adapter.rs +++ b/control/crates/layerfs-platform/src/platforms/native/adapter.rs @@ -4,7 +4,7 @@ use crate::adapter::{refused, Adapter}; use crate::error::MachineError; use crate::platform::HostOs; use crate::probe::native_missing; -use crate::reach::{dial, Loopback}; +use crate::reach::Loopback; use crate::setup::forward::shared; use crate::setup::guest::Guest; use crate::setup::Status; @@ -45,8 +45,8 @@ impl Adapter for Native { fn status(&self, _spec: &Spec) -> Result { status() } - fn reach(&self, spec: &Spec, url: &str) -> Result { - dial(spec, url, Loopback::Shared) + fn loopback(&self, _spec: &Spec) -> Loopback { + Loopback::Shared } /// The daemon is on this host's loopback: its port is used as it is. fn forward(&self, _spec: &Spec, guest_port: u16) -> Result { diff --git a/control/crates/layerfs-platform/src/reach.rs b/control/crates/layerfs-platform/src/reach.rs index 11a5968aaf..04927c25c7 100644 --- a/control/crates/layerfs-platform/src/reach.rs +++ b/control/crates/layerfs-platform/src/reach.rs @@ -1,71 +1,97 @@ //! `reach` (#535 §7.3, §7.4, G3): the PostgreSQL Store URL a Sandbox's daemon -//! on a machine dials. A URL whose host is the caller's loopback names a -//! server the machine sees under another name (its host alias); every -//! other host is dialled as given. Each platform's adapter -//! answers with [`dial`] and its own [`Loopback`]. +//! on a machine dials. The URL is dialled exactly as configured on every +//! machine: LayerFS rewrites no part of it and inspects no port (owner, +//! 2026-11-24). A machine that does not share the caller's loopback +//! refuses a URL naming that loopback, or a Unix socket of the caller, +//! naming what the machine calls this host and the per-machine URL +//! instead. Each platform's adapter declares its [`Loopback`]. //! //! The URL may hold the Store's password: no message here holds any part -//! of it. +//! of it but a loopback host. use crate::error::{Code, MachineError}; use crate::spec::Spec; -use layerfs_sandbox_backend::PostgresUrl; /// How a machine reaches the caller's loopback. -pub(crate) enum Loopback<'a> { - /// The daemon shares the caller's loopback: the URL is used as given. +pub(crate) enum Loopback { + /// The daemon shares it: the URL is used as given, unread. Shared, - /// The daemon reaches it under this host name or address. - Alias(&'a str), - /// The daemon reaches it under an address read from the machine, only - /// when a URL names the caller's loopback. - Lookup(&'a dyn Fn() -> Result), + /// The daemon does not share it: a URL naming it is refused, the + /// refusal naming how the machine reaches this host instead. + Apart(String), } -/// 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 { +/// The URL `spec`'s daemon dials for `url`, a URL of PostgreSQL Store +/// `store`, given how its machine reaches the caller's loopback: `url` +/// itself, or a refusal. Every host the URL names is checked, read as its +/// client reads them ([`layerfs_sandbox_backend::url_hosts`]): its host +/// list and its `host` and `hostaddr` parameters. Nothing is resolved: a +/// name is dialled as given. +pub(crate) fn dial( + spec: &Spec, + (store, url): (&str, &str), + loopback: Loopback, +) -> Result { + let Loopback::Apart(this_host) = loopback else { 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(|| { + }; + let hosts = layerfs_sandbox_backend::url_hosts(url).ok_or_else(|| { refuse( spec, Code::InvalidInput, - "its URL is not one postgres://[user@]host[:port]/... URL with one host", + "its URL is not one postgres://[user@]host[:port][,host[:port]...]/... URL its client reads, so the machine cannot check that it does not name this host's loopback", ) })?; - if parsed.query("host").chain(parsed.query("hostaddr")).count() > 0 { + let advice = advice(spec, store, &this_host); + if hosts + .iter() + .any(|host| layerfs_sandbox_backend::socket(host)) + { return Err(refuse( spec, Code::Unsupported, - "its URL names the server in a host or hostaddr parameter, which is not rewritten for a machine", + &format!("its URL names no host (a Unix socket of the caller), which no machine reaches; {advice}"), )); } - if parsed.host().is_empty() { - return Err(refuse( - spec, - Code::Unsupported, - "its URL names no host (a Unix socket of the caller), which no machine reaches", - )); - } - if !parsed.loopback() { - return Ok(url.to_owned()); - } - if parsed.query("sslmode").any(|mode| mode == "verify-full") { - return Err(refuse( + match hosts.iter().find(|host| layerfs_sandbox_backend::loopback(host)) { + None => Ok(url.to_owned()), + Some(host) => Err(refuse( spec, Code::Unsupported, - "its URL asks for sslmode=verify-full and names the caller's loopback, which this machine reaches under another name the server's certificate does not name; give the Store a URL whose host every machine can verify", - )); + &format!( + "its URL names this host's loopback ({host}), which the machine does not share; {advice}" + ), + )), } - let alias = match loopback { - Loopback::Alias(alias) => alias.to_owned(), - Loopback::Lookup(read) => read()?, - Loopback::Shared => unreachable!("answered above"), +} + +/// [`crate::loopback_hint`]: the refusal's advice, for a failed dial of a +/// name that resolves to a loopback address on the machine. Only a URL +/// naming at least one host by name can fail so: an address is read, never +/// resolved, and [`dial`] refused every loopback one. +pub(crate) fn hint(spec: &Spec, (store, url): (&str, &str), loopback: Loopback) -> Option { + let Loopback::Apart(this_host) = loopback else { + return None; + }; + let named = |host: &String| { + !layerfs_sandbox_backend::socket(host) && layerfs_sandbox_backend::ip(host).is_none() }; - Ok(parsed.with_host(&alias)) + if !layerfs_sandbox_backend::url_hosts(url)?.iter().any(named) { + return None; + } + Some(format!( + "if its host is a loopback address on the {} machine {} (a hosts entry can make a name one), the machine does not share this host's loopback; {}", + spec.kind.name(), + spec.name, + advice(spec, store, &this_host) + )) +} + +/// What to give a machine that does not share the caller's loopback. +fn advice(spec: &Spec, store: &str, this_host: &str) -> String { + format!( + "give the Store a host the machine reaches ({this_host}), or give the machine its own URL with `layerfs store connect {store} --machine {}`", + spec.name + ) } fn refuse(spec: &Spec, code: Code, why: &str) -> MachineError { diff --git a/control/crates/layerfs-platform/src/setup/calls.rs b/control/crates/layerfs-platform/src/setup/calls.rs index 42fc219636..fbb4af94dc 100644 --- a/control/crates/layerfs-platform/src/setup/calls.rs +++ b/control/crates/layerfs-platform/src/setup/calls.rs @@ -217,17 +217,31 @@ pub fn load_image(spec: &Spec, archive: &Path) -> Result { } /// The PostgreSQL Store URL a Sandbox daemon on `spec`'s machine dials for -/// `url` (#535 §7.3): `native` uses it as given; a loopback host becomes the -/// machine's host alias (`docker`: on Docker Desktop the address its running -/// worker container resolves `host.docker.internal` to, on a Linux Engine -/// the URL as given; `lima`: `192.168.5.2`, `apple-container`: its -/// network's gateway; -/// G7 receipts); a rewrite is refused when the URL asks for -/// `sslmode=verify-full`. Every other host is used as given. Starts nothing; -/// no message holds any part of the URL. -pub fn reach(spec: &Spec, url: &str) -> Result { +/// `url`, a URL of Store `store` (#535 §7.3): always `url` itself, never +/// rewritten (owner, 2026-11-24). A machine that does not share the +/// caller's loopback (`docker` on Docker Desktop, `lima`, +/// `apple-container`) refuses a loopback host `Unsupported`, naming what it +/// calls this host (`host.docker.internal`, `host.lima.internal`, the +/// network's gateway) and `layerfs store connect --machine +/// `; `native` and `docker` on a Linux Engine share it. Starts +/// nothing; no message holds any part of the URL but a loopback host. +pub fn reach(spec: &Spec, store: &str, url: &str) -> Result { spec.validate()?; - adapter(spec.kind).reach(spec, url) + crate::reach::dial(spec, (store, url), adapter(spec.kind).loopback(spec)) +} + +/// What a failed connection to Store `store` at `url` from `spec`'s machine +/// adds for its user, where it may be a loopback the machine does not +/// share: `Some` only on such a machine and only when the URL names a host +/// by name (an address is never resolved, and [`reach`] refused every +/// loopback one). A name that resolves to a loopback address there (a +/// hosts entry) is not refused up front, since nothing resolves a name to +/// check it, so the failure of its one dial carries the same advice as the +/// refusal. The caller adds it only when no connection was made, not when +/// the server answered (a refused login, say). Reads nothing from the +/// machine. +pub fn loopback_hint(spec: &Spec, store: &str, url: &str) -> Option { + crate::reach::hint(spec, (store, url), adapter(spec.kind).loopback(spec)) } /// The host loopback address at which this process reaches a Sandbox diff --git a/control/crates/layerfs-platform/src/setup/mod.rs b/control/crates/layerfs-platform/src/setup/mod.rs index d64c3cafb4..fff4d38b94 100644 --- a/control/crates/layerfs-platform/src/setup/mod.rs +++ b/control/crates/layerfs-platform/src/setup/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod worker; pub(crate) use calls::with_worker; pub use calls::{ cached_image, copy_in, copy_out, create, data_volume, forward, forward_close, load_image, - name_limit, provider_within, reach, remove, start, status, status_within, stop, stop_force, - worker_port, State, Status, + loopback_hint, name_limit, provider_within, reach, remove, start, status, status_within, stop, + stop_force, worker_port, State, Status, }; pub use tool::find_tool; diff --git a/control/crates/layerfs-platform/tests/conformance.rs b/control/crates/layerfs-platform/tests/conformance.rs index f1d4886c2a..b9894797fb 100644 --- a/control/crates/layerfs-platform/tests/conformance.rs +++ b/control/crates/layerfs-platform/tests/conformance.rs @@ -11,9 +11,10 @@ //! runs through the //! platform's provider tool (here, its stand-in) or is refused before any //! effect with the fixed refusal its `How` declares; -//! - `reach` against the §7.3 rules: a loopback host is shared or rewritten -//! to the platform's alias; a rewrite is refused for -//! `sslmode=verify-full`; every other host is dialled as given; no error +//! - `reach` against the §7.3 rules (owner, 2026-11-24): every URL is +//! dialled exactly as given, never rewritten, and no provider tool runs; +//! a loopback host the machine does not share is refused, naming the +//! machine's name for this host and `store connect --machine`; no error //! text or `Debug` holds the password; //! - `forward` (#535 G4): a daemon's port is used as it is, carried by a //! detached `ssh -L 127.0.0.1::127.0.0.1:` that @@ -353,20 +354,21 @@ const SECRET: &str = "kit-s3cr3t"; enum Loopback { /// The daemon shares it: the URL is used as given. Shared, - /// A loopback host becomes this host name or address. - Alias(String), + /// The daemon does not: a loopback URL is refused, naming this, what + /// the machine calls this host. + Apart(&'static str), } fn loopback(spec: &Spec) -> Loopback { match spec.kind { Platform::Native => Loopback::Shared, // a Linux Engine's worker shares the host's network; Docker - // Desktop's resolves `host.docker.internal` (`reach_spec`; D-8) + // Desktop's resolves `host.docker.internal` (D-8) Platform::Docker if cfg!(target_os = "linux") => Loopback::Shared, - Platform::Docker => Loopback::Alias("192.168.65.254".into()), - Platform::Lima => Loopback::Alias("192.168.5.2".into()), - // the gateway the stand-in `container inspect` reports (`reach_spec`) - Platform::AppleContainer => Loopback::Alias("192.168.64.1".into()), + Platform::Docker => Loopback::Apart("host.docker.internal"), + Platform::Lima => Loopback::Apart("host.lima.internal"), + // no name: the gateway its start recorded, else vmnet's default + Platform::AppleContainer => Loopback::Apart("192.168.64.1"), } } @@ -380,11 +382,13 @@ fn with_host(host: &str, query: &str) -> [String; 3] { } /// The same three URLs with each loopback host spelled differently. -fn loopback_urls(query: &str) -> [String; 3] { +fn loopback_urls(query: &str) -> [String; 5] { let [a, _, _] = with_host("127.0.0.1", query); let [_, b, _] = with_host("localhost", query); let [_, _, c] = with_host("[::1]", query); - [a, b, c] + let [d, _, _] = with_host("127.0.0.2", query); + let [_, e, _] = with_host("[::ffff:127.0.0.1]", query); + [a, b, c, d, e] } /// A refusal: its code and message; no part of the password in either its @@ -402,19 +406,11 @@ fn refused(platform: Platform, outcome: Result) -> (Code, (error.code, error.message) } -/// Each platform's spec for `reach`, its stand-in tools answering. +/// Each platform's spec for `reach`; every provider tool is a stand-in +/// that logs its call and fails, so a call shows in the log. fn reach_spec(scratch: &Scratch, platform: Platform) -> Spec { - if platform == Platform::AppleContainer { - scratch.tool( - "container", - r#"echo '[{"status":{"state":"running","networks":[{"ipv4Gateway":"192.168.64.1"}]}}]'"#, - ); - } - if platform == Platform::Docker { - scratch.tool( - "docker", - r#"printf '192.168.65.254 host.docker.internal\n'"#, - ); + for tool in ["docker", "container", "limactl"] { + scratch.tool(tool, "exit 1"); } valid_spec(scratch, platform) } @@ -428,82 +424,111 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { "the {} machine dev cannot reach the PostgreSQL Store's server: ", platform.name() ); - for query in ["", "?sslmode=disable", "?sslmode=verify-ca"] { - for (i, url) in loopback_urls(query).iter().enumerate() { - let outcome = machine::reach(&spec, url); + for query in [ + "", + "?sslmode=disable", + "?sslmode=verify-ca", + "?sslmode=verify-full", + ] { + for url in loopback_urls(query) { + let outcome = machine::reach(&spec, "pg", &url); match loopback(&spec) { - Loopback::Shared => assert_eq!(outcome.as_ref(), Ok(url)), - Loopback::Alias(alias) => assert_eq!( - outcome, - Ok(with_host(&alias, query)[i].clone()), - "{platform:?}" - ), - } - } - } - // the server's certificate names the loopback host, not an alias - for url in loopback_urls("?sslmode=verify-full") { - let outcome = machine::reach(&spec, &url); - match loopback(&spec) { - Loopback::Shared => assert_eq!(outcome, Ok(url)), - Loopback::Alias(_) => { - 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::Apart(name) => { + let (code, message) = refused(platform, outcome); + assert_eq!(code, Code::Unsupported, "{message}"); + assert!(message.starts_with(&prefix), "{message}"); + assert!(message.contains("loopback"), "{message}"); + assert!(message.contains(name), "{message}"); + assert!( + message.contains("layerfs store connect pg --machine dev"), + "{message}" + ); + } } } } } + assert_eq!(scratch.log(), "", "reach runs no provider tool"); } #[test] fn every_other_server_is_dialled_as_given_on_every_platform() { let scratch = Scratch::new("kit-reach-remote"); let urls = [ + // nothing is rewritten, so a certificate's name is never lost format!("postgres://lfs:{SECRET}@db.example.com:5432/layerfs?sslmode=verify-full"), + format!("postgres://lfs:{SECRET}@host.docker.internal:5432/layerfs?sslmode=verify-full"), + format!("postgresql://lfs:{SECRET}@host.lima.internal/layerfs"), format!("postgresql://lfs:{SECRET}@10.0.0.5/layerfs"), "postgres://[2001:db8::1]:5432/layerfs".to_owned(), - // only the three loopback names are rewritten - "postgres://u@127.0.0.2/db".to_owned(), + format!("postgres://lfs:{SECRET}@h1:5432,h2:5433/db"), + format!("postgres://lfs:{SECRET}@db/layerfs?hostaddr=10.0.0.5"), + format!("postgres://lfs:{SECRET}@h1:5432,h2/db"), ]; for platform in Platform::ALL { let spec = reach_spec(&scratch, platform); for url in &urls { - assert_eq!(machine::reach(&spec, url).as_ref(), Ok(url), "{platform:?}"); + assert_eq!( + machine::reach(&spec, "pg", url).as_ref(), + Ok(url), + "{platform:?}" + ); } } + assert_eq!(scratch.log(), "", "reach runs no provider tool"); } #[test] -fn a_url_reach_cannot_rewrite_is_refused_unless_the_loopback_is_shared() { +fn a_url_reach_cannot_check_is_refused_unless_the_loopback_is_shared() { let scratch = Scratch::new("kit-reach-unread"); let cases = [ + // libpq's key=value words are no Store URL (`secrets::parts` + // refuses them before reach): not read ( format!("host=localhost user=lfs password={SECRET}"), Code::InvalidInput, ), - ( - format!("postgres://lfs:{SECRET}@h1:5432,h2:5433/db"), - Code::InvalidInput, - ), + (format!("localhost {SECRET}"), Code::InvalidInput), ( format!("postgres://lfs:{SECRET}@/layerfs"), Code::Unsupported, ), + ( + format!("dbname=layerfs password={SECRET}"), + Code::InvalidInput, + ), ( format!("postgres:///layerfs?host=/var/run/postgresql&password={SECRET}"), Code::Unsupported, ), + // a loopback host in a parameter or a host list is refused too ( format!("postgres://lfs:{SECRET}@db/layerfs?hostaddr=127.0.0.1"), Code::Unsupported, ), + ( + format!("postgres://lfs:{SECRET}@h1:5432,localhost:5433/db"), + Code::Unsupported, + ), + // read as the client reads it: percent-decoded, the list split first + ( + format!("postgres://lfs:{SECRET}@%6Cocalhost/db"), + Code::Unsupported, + ), + ( + format!("postgres://lfs:{SECRET}@[::1]:5432,h2/db"), + Code::Unsupported, + ), + ( + format!("postgres://lfs:{SECRET}@db/x?h%6Fst=127.1"), + Code::Unsupported, + ), ]; for platform in Platform::ALL { let spec = reach_spec(&scratch, platform); for (url, code) in &cases { - let outcome = machine::reach(&spec, url); + let outcome = machine::reach(&spec, "pg", url); if matches!(loopback(&spec), Loopback::Shared) { assert_eq!(outcome.as_ref(), Ok(url), "{platform:?}"); } else { @@ -512,6 +537,7 @@ fn a_url_reach_cannot_rewrite_is_refused_unless_the_loopback_is_shared() { } } } + assert_eq!(scratch.log(), "", "reach runs no provider tool"); } // --------------------------------------------------------------------------- diff --git a/control/crates/layerfs-platform/tests/localhost_reach.rs b/control/crates/layerfs-platform/tests/localhost_reach.rs index be30bc4b6e..ee9d4c9ed8 100644 --- a/control/crates/layerfs-platform/tests/localhost_reach.rs +++ b/control/crates/layerfs-platform/tests/localhost_reach.rs @@ -37,7 +37,7 @@ fn native_and_docker_dial_every_url_as_given() { for kind in [Platform::Native, Platform::Docker] { let spec = scratch.spec(kind); for url in urls() { - let outcome = machine::reach(&spec, &url); + let outcome = machine::reach(&spec, "pg", &url); if outcome.as_deref() != Ok(url.as_str()) { changed.push(format!("{kind:?} {url} -> {outcome:?}")); } diff --git a/control/crates/layerfs-platform/tests/machine_reach.rs b/control/crates/layerfs-platform/tests/machine_reach.rs index f0fb37e49f..ab85a63fc8 100644 --- a/control/crates/layerfs-platform/tests/machine_reach.rs +++ b/control/crates/layerfs-platform/tests/machine_reach.rs @@ -1,10 +1,13 @@ -//! `reach` (#535 §7.3, §7.4): the PostgreSQL Store URL a Sandbox daemon on -//! each platform dials. A loopback host becomes the platform's host alias or -//! is refused naming what is missing; a rewrite is refused for -//! `sslmode=verify-full`; every other host is dialled as given. No message -//! holds the URL's password. Only apple-container's stand-in `container` -//! and docker's stand-in `docker` run, and only for a loopback URL (they -//! read the network's gateway, and what the worker resolves its host to). +//! `reach` (#535 §7.3, §7.4; owner 2026-11-24): the PostgreSQL Store URL a +//! Sandbox daemon on each platform dials, which is the URL as configured, +//! never rewritten. A machine that does not share the caller's loopback +//! (docker on Docker Desktop, lima, apple-container) refuses a loopback host, +//! naming its own name for this host and `store connect --machine`; +//! every other URL is dialled as given, `sslmode=verify-full` included. Hosts +//! are read as the client (tokio-postgres) reads them: percent-decoded, a +//! host list split at `,` first, every IPv4 form `inet_aton` reads. No +//! message holds the URL's password, and no provider tool runs: every +//! stand-in here logs its call and fails. #![cfg(unix)] #[path = "support/standin.rs"] mod standin; @@ -13,21 +16,26 @@ use standin::Scratch; const SECRET: &str = "s3cr3t-pw"; -/// `container inspect` of a running container on vmnet's default network, -/// as `container` 1.6.1 prints it (G7 receipt `ac-inspect.json`, cut). -const RUNNING: &str = r#"echo '[{"status":{"state":"running","networks":[{"network":"default","ipv4Address":"192.168.64.10/24","ipv4Gateway":"192.168.64.1"}]}}]'"#; +/// The Store every URL here belongs to, which the refusal's advice names. +const STORE: &str = "pg"; + +/// [`machine::reach`] of Store [`STORE`]. +fn reach(spec: &Spec, url: &str) -> Result { + machine::reach(spec, STORE, url) +} + +/// The per-machine URL call every refusal on machine `dev` advises. +const CONNECT: &str = "`layerfs store connect pg --machine dev`"; /// `getent ahostsv4 host.docker.internal` in a Docker Desktop worker -/// container (D-8 live receipt): its DNS answers the name. -const RESOLVED: &str = r#"printf '192.168.65.254 STREAM host.docker.internal\n192.168.65.254 DGRAM \n192.168.65.254 RAW \n'"#; +/// container (D-8 live receipt), which the former lookup ran per call. +const RESOLVED: &str = r#"printf '192.168.65.254 STREAM host.docker.internal\n'"#; -/// `kind`'s spec as `standin` makes it. +/// `kind`'s spec as `standin` makes it, every provider tool a stand-in that +/// logs its call and fails. fn spec(scratch: &Scratch, kind: Platform) -> Spec { - if kind == Platform::AppleContainer { - scratch.tool("container", RUNNING); - } - if kind == Platform::Docker { - scratch.tool("docker", RESOLVED); + for tool in ["docker", "container", "limactl"] { + scratch.tool(tool, "exit 1"); } scratch.spec(kind) } @@ -49,176 +57,287 @@ fn loopback_urls() -> [String; 3] { ] } -/// The URL with `host` for its loopback host, as the three above. -fn rewritten(host: &str) -> [String; 3] { - [ - format!("postgres://lfs:{SECRET}@{host}:5432/layerfs?sslmode=disable"), - format!("postgresql://lfs:{SECRET}@{host}/layerfs"), - format!("postgres://lfs:{SECRET}@{host}:6543/layerfs"), +/// What each platform calls this host in its refusal of a loopback URL; +/// `None` where the loopback is shared. +fn this_host(kind: Platform) -> Option<&'static str> { + match kind { + Platform::Native => None, + // a Linux Engine's worker shares the host's network (D-8) + Platform::Docker if cfg!(target_os = "linux") => None, + Platform::Docker => Some("host.docker.internal"), + Platform::Lima => Some("host.lima.internal"), + Platform::AppleContainer => Some("192.168.64.1"), + } +} + +/// Every spelling of this host's loopback, as the URL's host, and the +/// host the refusal names. +fn loopback_forms() -> Vec<(String, &'static str)> { + let at = |host: &str| format!("postgres://lfs:{SECRET}@{host}/layerfs"); + vec![ + (loopback_urls()[0].clone(), "127.0.0.1"), + (loopback_urls()[1].clone(), "localhost"), + (loopback_urls()[2].clone(), "::1"), + (at("LocalHost"), "LocalHost"), + (at("localhost."), "localhost."), + // the whole of 127.0.0.0/8 + (at("127.0.0.2:5432"), "127.0.0.2"), + (at("127.255.255.254"), "127.255.255.254"), + // IPv4-mapped + (at("[::ffff:127.0.0.1]:5432"), "::ffff:127.0.0.1"), + (at("[0:0:0:0:0:0:0:1]"), "0:0:0:0:0:0:0:1"), + // every host of a list, and the host parameters + (at("db1:5432,localhost:5433"), "localhost"), + (at("db1:5432,[::1]:5433"), "::1"), + (format!("{}?host=127.0.0.1", at("db1")), "127.0.0.1"), + (format!("{}?hostaddr=127.0.0.1", at("db1")), "127.0.0.1"), + (format!("{}?host=db2,localhost", at("db1")), "localhost"), + // a list splits at `,` before a host's port or brackets are read, + // as the client splits it: a bracketed host need not be last + (at("[::1]:5432,h2"), "::1"), + (at("h1,[::1]"), "::1"), + (at("h1:5432,127.0.0.1"), "127.0.0.1"), + // the userinfo ends at the first `@`, so a password's unescaped + // `/` does not hide the host after it + ( + format!("postgres://lfs:{SECRET}/x@localhost/db"), + "localhost", + ), + // percent-encoded hosts, `host`/`hostaddr` values and keys are + // decoded, as the client decodes them before it dials + (at("%6Cocalhost"), "localhost"), + (at("%31%32%37.0.0.1:5432"), "127.0.0.1"), + (format!("{}?host=%6Cocalhost", at("db1")), "localhost"), + (format!("{}?h%6Fst=localhost", at("db1")), "localhost"), + ( + format!("{}?hostaddr=%31%32%37.0.0.1", at("db1")), + "127.0.0.1", + ), + (format!("{}?%68ostaddr=::1", at("db1")), "::1"), + // the unspecified address reaches this host + (at("0.0.0.0"), "0.0.0.0"), + (at("[::]:5432"), "::"), + (at("[::ffff:0.0.0.0]"), "::ffff:0.0.0.0"), + (format!("{}?hostaddr=0.0.0.0", at("db1")), "0.0.0.0"), + // the IPv4 forms `inet_aton` reads, which `getaddrinfo` dials + (at("127.1"), "127.1"), + (at("127.0.1"), "127.0.1"), + (at("2130706433"), "2130706433"), + (at("127.000.000.001"), "127.000.000.001"), + (at("0x7f.1"), "0x7f.1"), + (at("0X7F000001"), "0X7F000001"), + (at("017700000001"), "017700000001"), + (at("0177.0.0.1"), "0177.0.0.1"), + (at("0"), "0"), + (format!("{}?host=127.1", at("db1")), "127.1"), + // an IPv6 zone id + (at("[::1%25lo]:5432"), "::1%lo"), + (format!("{}?host=::1%25lo", at("db1")), "::1%lo"), + (format!("{}?host=fe80::1,::1%lo0", at("db1")), "::1%lo0"), ] } #[test] -fn each_platform_rewrites_a_loopback_host() { +fn a_loopback_host_is_refused_where_the_loopback_is_not_shared() { let scratch = Scratch::new("reach-loopback"); for kind in Platform::ALL { let spec = spec(&scratch, kind); - let alias = match kind { - Platform::Native => "unchanged", - // a Linux Engine's worker shares the host's network (D-8) - Platform::Docker if cfg!(target_os = "linux") => "unchanged", - Platform::Docker => "192.168.65.254", - Platform::Lima => "192.168.5.2", - Platform::AppleContainer => "192.168.64.1", - }; - for (i, url) in loopback_urls().iter().enumerate() { - let outcome = machine::reach(&spec, url); - match alias { - "unchanged" => assert_eq!(outcome.as_deref(), Ok(url.as_str())), - alias => assert_eq!(outcome, Ok(rewritten(alias)[i].clone()), "{kind:?}"), - } + for (url, host) in loopback_forms() { + let outcome = reach(&spec, &url); + let Some(name) = this_host(kind) else { + assert_eq!(outcome.as_deref(), Ok(url.as_str()), "{kind:?}"); + continue; + }; + let (code, message) = refused(outcome); + assert_eq!(code, Code::Unsupported, "{url}: {message}"); + assert!( + message.contains(&format!("names this host's loopback ({host})")), + "{message}" + ); + assert!(message.contains(name), "{message}"); + assert!(message.contains(CONNECT), "{message}"); } } + assert_eq!(scratch.log(), "", "no provider tool runs"); } +/// A Unix socket of the caller (no host, or a host that is a path) never +/// reaches a machine that does not share this host: refused with the same +/// advice; `native` (and a Linux Engine) dial it as given. #[test] -fn apple_container_reads_its_gateway_only_for_a_loopback_url() { - let scratch = Scratch::new("reach-apple"); - let spec = spec(&scratch, Platform::AppleContainer); - let remote = format!("postgres://lfs:{SECRET}@db.example.com:5432/layerfs"); - assert_eq!(machine::reach(&spec, &remote), Ok(remote.clone())); - assert_eq!(scratch.log(), "", "a remote URL reads nothing"); - let outcome = machine::reach(&spec, &loopback_urls()[1]); - assert_eq!(outcome, Ok(rewritten("192.168.64.1")[1].clone())); - assert_eq!(scratch.log(), "container inspect lfs-dev\n"); - // a stopped container reports no network: refused, naming why - scratch.tool( - "container", - r#"echo '[{"status":{"state":"stopped","networks":[]}}]'"#, - ); - let (code, message) = refused(machine::reach(&spec, &loopback_urls()[0])); - assert_eq!(code, Code::Unavailable); - assert!(message.contains("reports no network gateway"), "{message}"); - assert!(message.contains("must be running"), "{message}"); - // an answer that is not an IPv4 address is not put in the URL - scratch.tool( - "container", - r#"echo '[{"status":{"networks":[{"ipv4Gateway":"evil/x@y"}]}}]'"#, - ); - let (code, _) = refused(machine::reach(&spec, &loopback_urls()[0])); - assert_eq!(code, Code::Unavailable); +fn a_unix_socket_is_refused_where_the_loopback_is_not_shared() { + let scratch = Scratch::new("reach-socket"); + let urls = [ + format!("postgres://lfs:{SECRET}@/layerfs"), + format!("postgres:///layerfs?host=/var/run/postgresql&password={SECRET}"), + "postgresql://%2Fvar%2Frun%2Fpostgresql/layerfs".to_owned(), + // a socket directory named by a host parameter, encoded or not + "postgres://db1/layerfs?host=%2Ftmp".to_owned(), + "postgres://db1/layerfs?h%6Fst=/tmp".to_owned(), + ]; + for kind in Platform::ALL { + let spec = spec(&scratch, kind); + for url in &urls { + let outcome = reach(&spec, url); + let Some(name) = this_host(kind) else { + assert_eq!(outcome.as_ref(), Ok(url), "{kind:?}"); + continue; + }; + let (code, message) = refused(outcome); + assert_eq!(code, Code::Unsupported, "{url}: {message}"); + assert!(message.contains("a Unix socket of the caller"), "{message}"); + assert!(message.contains(name), "{message}"); + assert!(message.contains(CONNECT), "{message}"); + } + } +} + +/// A name that resolves to a loopback address on the machine (a hosts +/// entry) is not resolved to be refused up front: its one dial fails, and +/// the failure carries this hint, the refusal's own advice. A shared +/// loopback has none, and neither has a URL naming no host by name: an +/// address is read, never resolved, so only a name can turn out to be +/// this host's loopback. +#[test] +fn a_failed_dial_carries_the_loopback_hint_where_it_is_not_shared() { + let scratch = Scratch::new("reach-hint"); + let named = format!("postgres://lfs:{SECRET}@db.example.com:5432/layerfs"); + for kind in Platform::ALL { + let spec = spec(&scratch, kind); + let hint = machine::loopback_hint(&spec, STORE, &named); + for addressed in [ + format!("postgres://lfs:{SECRET}@10.0.0.5:5432/layerfs"), + format!("postgres://lfs:{SECRET}@[2001:db8::1],10.1/layerfs"), + format!("postgres://lfs:{SECRET}@10.0.0.5/layerfs?hostaddr=10.0.0.6"), + ] { + assert_eq!(machine::loopback_hint(&spec, STORE, &addressed), None); + } + // one name among addresses can still be a loopback one + let mixed = format!("postgres://lfs:{SECRET}@10.0.0.5,db.example.com/layerfs"); + assert_eq!(machine::loopback_hint(&spec, STORE, &mixed), hint); + let Some(name) = this_host(kind) else { + assert_eq!(hint, None, "{kind:?}"); + continue; + }; + let hint = hint.unwrap(); + assert!(!hint.contains(SECRET), "{hint}"); + assert!(hint.contains("loopback address"), "{hint}"); + assert!(hint.contains(name), "{hint}"); + assert!(hint.contains(CONNECT), "{hint}"); + // the same advice as the up-front refusal + let (_, message) = refused(reach(&spec, &loopback_urls()[0])); + let advice = &hint[hint.find("give the Store").unwrap()..]; + assert!(message.ends_with(advice), "{message} / {hint}"); + } + assert_eq!(scratch.log(), "", "no provider tool runs"); +} + +/// The per-call cost of D-8 (#758 B6): every docker Sandbox call on a +/// PostgreSQL Store ran `docker exec getent ahostsv4 +/// host.docker.internal` in the caller. No URL is rewritten now, so no +/// `docker` command runs, whatever the URL names; the worker's own `docker` +/// answering changes nothing. +#[test] +fn a_docker_sandbox_call_runs_no_docker_command() { + let scratch = Scratch::new("reach-docker"); + let spec = spec(&scratch, Platform::Docker); + scratch.tool("docker", RESOLVED); + let named = format!("postgres://lfs:{SECRET}@host.docker.internal:5432/layerfs"); + for _call in 0..3 { + assert_eq!(reach(&spec, &named), Ok(named.clone())); + let outcome = reach(&spec, &loopback_urls()[0]); + match cfg!(target_os = "linux") { + true => assert_eq!(outcome, Ok(loopback_urls()[0].clone())), + false => assert_eq!(refused(outcome).0, Code::Unsupported), + } + } + assert_eq!(scratch.log(), "", "no docker command runs"); } -/// #66: a gateway its last start recorded is used with no `container` -/// call; a stale one is dialled as recorded (the connection then fails, -/// explicitly), never looked up again. A record without one (from before -/// #66) still reads it from the machine. +/// apple-container has no name for this host: its refusal names the +/// gateway its last start recorded (#66), else vmnet's default, read from +/// no `container` call. #[test] -fn apple_container_uses_the_gateway_its_start_recorded() { +fn apple_container_names_its_recorded_gateway() { let scratch = Scratch::new("reach-apple-recorded"); let mut spec = spec(&scratch, Platform::AppleContainer); spec.state.gateway = Some("192.168.65.1".parse().unwrap()); - for (url, want) in loopback_urls().iter().zip(rewritten("192.168.65.1")) { - assert_eq!(machine::reach(&spec, url), Ok(want)); - } - assert_eq!( - scratch.log(), - "", - "no container inspect with a recorded gateway" + let (_, message) = refused(reach(&spec, &loopback_urls()[0])); + assert!( + message.contains("192.168.65.1, on which the server must listen"), + "{message}" ); spec.state.gateway = None; - let outcome = machine::reach(&spec, &loopback_urls()[0]); - assert_eq!(outcome, Ok(rewritten("192.168.64.1")[0].clone())); - assert_eq!(scratch.log(), "container inspect lfs-dev\n"); + let (_, message) = refused(reach(&spec, &loopback_urls()[0])); + assert!(message.contains("192.168.64.1"), "{message}"); + assert_eq!(scratch.log(), "", "no container inspect"); } #[test] fn every_other_host_is_dialled_as_given_everywhere() { let scratch = Scratch::new("reach-remote"); let urls = [ + // nothing is rewritten, so the server's certificate check holds format!("postgres://lfs:{SECRET}@db.example.com:5432/layerfs?sslmode=verify-full"), + format!("postgres://lfs:{SECRET}@host.docker.internal/layerfs?sslmode=verify-full"), + format!("postgres://lfs:{SECRET}@host.lima.internal/layerfs?sslmode=verify-ca"), "postgresql://lfs@10.0.0.5/layerfs".to_owned(), "postgres://[2001:db8::1]:5432/layerfs".to_owned(), - // only the three loopback names are rewritten - "postgres://u@127.0.0.2/db".to_owned(), + format!("postgres://lfs:{SECRET}@h1:5432,h2:5433/db"), + // valid host lists: a port on some hosts only, a bracketed host + // anywhere in the list + format!("postgres://lfs:{SECRET}@h1:5432,h2/db"), + format!("postgres://lfs:{SECRET}@h1,[2001:db8::1]/db"), + format!("postgres://lfs:{SECRET}@[2001:db8::1]:5432,h2/db"), + // the host parameters are dialled as given once checked + format!("postgres://lfs:{SECRET}@db/layerfs?hostaddr=10.0.0.5&host=db2"), + // a URL with no host of its own, naming one by parameter + format!("postgres:///layerfs?host=db2&password={SECRET}"), + // addresses `inet_aton` reads that are not this host's loopback + "postgres://u@10.1/db".to_owned(), + "postgres://u@0x80.1/db".to_owned(), + "postgres://u@[fe80::1%25eth0]/db".to_owned(), + // ports are never read: a host's port is the server's + "postgres://u@10.0.0.5:5432/db".to_owned(), + // a name is never resolved, even one only this host could + "postgres://u@localhost.example.com/db".to_owned(), + "postgres://u@128.0.0.1/db".to_owned(), ]; for kind in Platform::ALL { let spec = spec(&scratch, kind); for url in &urls { - assert_eq!(machine::reach(&spec, url).as_ref(), Ok(url), "{kind:?}"); + assert_eq!(reach(&spec, url).as_ref(), Ok(url), "{kind:?}"); } } + assert_eq!(scratch.log(), "", "no provider tool runs"); } #[test] -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], - false => &[Platform::Docker, Platform::Lima], - }; - for &kind in rewriting { - let (code, message) = refused(machine::reach(&spec(&scratch, kind), &url)); - 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()) - ); - // verify-ca does not check the host name - let ca = url.replace("verify-full", "verify-ca"); - assert_eq!( - machine::reach(&spec(&scratch, Platform::Lima), &ca), - Ok(ca.replace("localhost", "192.168.5.2")) - ); -} - -#[test] -fn a_url_reach_cannot_read_is_refused_off_native() { +fn a_url_reach_cannot_read_is_refused_off_a_shared_loopback() { let scratch = Scratch::new("reach-unread"); - // lima rewrites a loopback host on every host OS + // lima does not share the loopback on any host OS let lima = spec(&scratch, Platform::Lima); let native = spec(&scratch, Platform::Native); - for (url, code, why) in [ - ( - format!("host=localhost user=lfs password={SECRET}"), - Code::InvalidInput, - "not one postgres://", - ), - ( - format!("postgres://lfs:{SECRET}@h1:5432,h2:5433/db"), - Code::InvalidInput, - "not one postgres://", - ), - // a password with an unescaped `/` cuts the authority: not read - ( - format!("postgres://lfs:{SECRET}/x@localhost/db"), - Code::InvalidInput, - "not one postgres://", - ), - ( - format!("postgres://lfs:{SECRET}@/layerfs"), - Code::Unsupported, - "names no host", - ), - ( - format!("postgres:///layerfs?host=/var/run/postgresql&password={SECRET}"), - Code::Unsupported, - "host or hostaddr parameter", - ), - ( - format!("postgres://lfs:{SECRET}@db/layerfs?hostaddr=127.0.0.1"), - Code::Unsupported, - "host or hostaddr parameter", - ), + for url in [ + // not a postgres:// URL: libpq's key=value words are never a + // Store's URL (`secrets::parts` refuses them), nor are other words + format!("host=localhost user=lfs password={SECRET}"), + format!("dbname=layerfs password={SECRET}"), + format!("host=db.example.com port=5433 password='p w{SECRET}'"), + format!("localhost {SECRET}"), + format!("host='localhost password={SECRET}"), + format!("mysql://lfs:{SECRET}@db/x"), + // what the client itself refuses to read + format!("postgres://lfs:{SECRET}@[::1/db"), + format!("postgres://lfs:{SECRET}@[::1]x/db"), + format!("postgres://lfs:{SECRET}@db/x?sslmode"), + format!("postgres://lfs:{SECRET}@%FF/x"), + format!("postgres://lfs:{SECRET}@db/x?%FF=localhost"), ] { - let (got, message) = refused(machine::reach(&lima, &url)); - assert_eq!(got, code, "{message}"); - assert!(message.contains(why), "{message}"); - assert_eq!(machine::reach(&native, &url).as_ref(), Ok(&url)); + let (got, message) = refused(reach(&lima, &url)); + assert_eq!(got, Code::InvalidInput, "{message}"); + assert!(message.contains("cannot check"), "{message}"); + assert_eq!(reach(&native, &url).as_ref(), Ok(&url)); } } @@ -227,43 +346,7 @@ fn an_invalid_spec_is_refused_before_the_url_is_read() { let scratch = Scratch::new("reach-spec"); let mut spec = spec(&scratch, Platform::Docker); spec.name = "not plain".into(); - let (code, message) = refused(machine::reach(&spec, &loopback_urls()[0])); + let (code, message) = refused(reach(&spec, &loopback_urls()[0])); assert_eq!(code, Code::InvalidInput); assert!(message.contains("not a plain name"), "{message}"); } - -/// D-8: a docker Sandbox runs in the Sandbox image's root, which cannot -/// resolve `host.docker.internal`, so a loopback URL gets the address the -/// running worker container resolves the name to. Only a loopback URL -/// reads it; a stopped worker, or one resolving no IPv4 address, is refused -/// `Unavailable` and puts nothing in the URL. -#[cfg(not(target_os = "linux"))] -#[test] -fn docker_reads_its_worker_s_host_address_only_for_a_loopback_url() { - let scratch = Scratch::new("reach-docker"); - let spec = spec(&scratch, Platform::Docker); - let remote = format!("postgres://lfs:{SECRET}@db.example.com:5432/layerfs"); - assert_eq!(machine::reach(&spec, &remote), Ok(remote.clone())); - assert_eq!(scratch.log(), "", "a remote URL reads nothing"); - let outcome = machine::reach(&spec, &loopback_urls()[1]); - assert_eq!(outcome, Ok(rewritten("192.168.65.254")[1].clone())); - assert_eq!( - scratch.log(), - "docker -H unix:///var/run/docker.sock exec lfs-dev getent ahostsv4 host.docker.internal\n" - ); - // a worker that is not running resolves nothing - scratch.tool( - "docker", - r#"echo "Error response from daemon: container lfs-dev is not running" >&2; exit 1"#, - ); - let (code, message) = refused(machine::reach(&spec, &loopback_urls()[0])); - assert_eq!(code, Code::Unavailable); - assert!(message.contains("must be running"), "{message}"); - // an unresolved name (getent exits 2), or an answer that is not an - // IPv4 address, is not put in the URL - for body in ["exit 2", r#"echo 'evil/x@y STREAM host.docker.internal'"#] { - scratch.tool("docker", body); - let (code, _) = refused(machine::reach(&spec, &loopback_urls()[0])); - assert_eq!(code, Code::Unavailable); - } -} diff --git a/control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs b/control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs index eabb045459..7fb51d1796 100644 --- a/control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs +++ b/control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs @@ -6,7 +6,10 @@ //! path keeps one meaning on both sides of the pivot, and a //! private `/proc`, `/dev` and `/tmp` are mounted over the image's own. //! The Sandbox's copy of the bundle's runtime layer, when its spec names one, -//! is bound read-only, nosuid and nodev at `/.layerfs/runtime` (R5). +//! is bound read-only, nosuid and nodev at `/.layerfs/runtime` (R5). This +//! host's `/etc/resolv.conf` and `/etc/hosts` are bound read-only over the +//! image's, so the Sandbox, which shares this host's network, resolves names +//! as this host does. //! Nothing the Sandbox mounts reaches the VM's mount tree: the init stage made //! this mount namespace private first. use layerfs_sandbox_backend::HelperSpec; @@ -67,9 +70,65 @@ pub(super) fn build(spec: &HelperSpec) -> Result<(), String> { if let Some(runtime) = &spec.runtime { bind_runtime(runtime, &spec.root)?; } + resolver(spec) +} + +/// This host's [`RESOLVER_FILES`], each bound read-only at its own path in +/// the root, over the image's file. A mount point the image lacks (its copy +/// leaves both files out) is made empty, 0644, in the Sandbox's own +/// writable layer, and one that is a link or another non-file is replaced +/// there. An image whose `/etc` is not a plain directory keeps its own +/// files (a bind through a link would leave the root before the pivot); so +/// does one whose entry is a directory. A file this host lacks is not bound. +/// +/// [`RESOLVER_FILES`]: layerfs_sandbox_backend::RESOLVER_FILES +fn resolver(spec: &HelperSpec) -> Result<(), String> { + let targets = spec.resolver_targets()?; + let etc = spec.root.join("etc"); + match fs::symlink_metadata(&etc) { + Ok(metadata) if metadata.is_dir() => {} + Ok(_) => return Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => directory(&etc, 0o755)?, + Err(error) => return Err(format!("{}: {error}", etc.display())), + } + for source in targets { + if !fs::metadata(&source).is_ok_and(|metadata| metadata.is_file()) { + continue; + } + let target = inside_file(&spec.root, &source); + match fs::symlink_metadata(&target) { + Ok(metadata) if metadata.is_file() => {} + Ok(metadata) if metadata.is_dir() => continue, + Ok(_) => { + fs::remove_file(&target) + .map_err(|error| format!("{}: {error}", target.display()))?; + empty_file(&target)?; + } + Err(error) if error.kind() == io::ErrorKind::NotFound => empty_file(&target)?, + Err(error) => return Err(format!("{}: {error}", target.display())), + } + bind(&source, &target, true)?; + } Ok(()) } +/// `path`'s place inside `root`, not made: `/a/b` becomes `/a/b`. +fn inside_file(root: &Path, path: &Path) -> PathBuf { + root.join(path.strip_prefix("/").unwrap_or(path)) +} + +/// An empty 0644 file at `path`, a bind's mount point. +fn empty_file(path: &Path) -> Result<(), String> { + use std::os::unix::fs::OpenOptionsExt; + fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(path) + .map(drop) + .map_err(|error| format!("{}: {error}", path.display())) +} + /// The runtime layer at `source`, bound read-only, nosuid and nodev at /// [`RUNTIME`] inside `root`. Its mount point is made in the Sandbox's own /// writable layer; an image whose `/.layerfs` or `/.layerfs/runtime` is not diff --git a/control/crates/layerfs-sandbox-backend/src/helper_spec.rs b/control/crates/layerfs-sandbox-backend/src/helper_spec.rs index 12bb8d0566..92ad803e8e 100644 --- a/control/crates/layerfs-sandbox-backend/src/helper_spec.rs +++ b/control/crates/layerfs-sandbox-backend/src/helper_spec.rs @@ -38,6 +38,15 @@ const BIND: &str = "bind"; /// The key of the optional runtime line, written once after the fields. const RUNTIME: &str = "runtime"; +/// The launcher's name-resolution files, which the init stage binds +/// read-only over the Sandbox root's own: the Sandbox shares the launcher's +/// network namespace, so it then resolves names as the launcher does +/// (Docker Desktop's `host.docker.internal`, a VM's hosts entries, any DNS +/// name). Their place is the root's `/etc`, the image and the Sandbox's own +/// writable layer, never a Workspace: Workspaces are mounted under the +/// Sandbox directory, and a diff or a Commit reads nothing else. +pub const RESOLVER_FILES: [&str; 2] = ["/etc/resolv.conf", "/etc/hosts"]; + /// One init stage's decoded inputs. #[derive(Clone, Debug, Eq, PartialEq)] pub struct HelperSpec { @@ -73,6 +82,28 @@ pub struct HelperSpec { } impl HelperSpec { + /// The guest paths the init stage binds [`RESOLVER_FILES`] at. Refused + /// when one would land in the Sandbox directory (where its Workspaces + /// are mounted) or in a bind, which a resolver file must never enter. + pub fn resolver_targets(&self) -> Result, String> { + let mounted = + std::iter::once(&self.sandbox).chain(self.binds.iter().map(|bind| &bind.guest)); + let mounted: Vec<&PathBuf> = mounted.collect(); + let mut targets = Vec::new(); + for file in RESOLVER_FILES { + let target = PathBuf::from(file); + if let Some(holder) = mounted.iter().find(|path| target.starts_with(path)) { + return Err(format!( + "{} is inside {}, which the Sandbox mounts, so the resolver files cannot be bound", + target.display(), + holder.display() + )); + } + targets.push(target); + } + Ok(targets) + } + /// Encodes the fields and the binds; refuses a path that is not /// absolute, has `.` or `..` components, or holds a control character. pub fn encode(&self) -> Result, RuntimeError> { diff --git a/control/crates/layerfs-sandbox-backend/src/lib.rs b/control/crates/layerfs-sandbox-backend/src/lib.rs index 825c73eaf0..58c38cbcf3 100644 --- a/control/crates/layerfs-sandbox-backend/src/lib.rs +++ b/control/crates/layerfs-sandbox-backend/src/lib.rs @@ -42,9 +42,9 @@ pub mod local; #[cfg(target_os = "macos")] pub use backend::host_process::HostProcessProvider; #[cfg(unix)] -pub use helper_spec::HelperSpec; +pub use helper_spec::{HelperSpec, RESOLVER_FILES}; #[cfg(unix)] -pub use postgres_url::PostgresUrl; +pub use postgres_url::{ip, loopback, socket, url_hosts}; #[cfg(any(target_os = "linux", target_os = "macos"))] pub use runtime::{LaunchFailure, Runtime, Sandbox}; #[cfg(any(target_os = "linux", target_os = "macos"))] diff --git a/control/crates/layerfs-sandbox-backend/src/postgres_url.rs b/control/crates/layerfs-sandbox-backend/src/postgres_url.rs index 624dd721c5..f6bf8f47a9 100644 --- a/control/crates/layerfs-sandbox-backend/src/postgres_url.rs +++ b/control/crates/layerfs-sandbox-backend/src/postgres_url.rs @@ -1,90 +1,203 @@ -//! A PostgreSQL connection URL (`postgres://` or `postgresql://`) split at -//! its host, so a Sandbox's daemon can be given the same URL under another -//! host name (Docker Desktop's `host.docker.internal`, a machine's alias). +//! The hosts a PostgreSQL connection URL (`postgres://` or `postgresql://`) +//! names, read exactly as its client reads them, so that a machine that +//! does not share the caller's loopback can refuse a URL naming it (the URL +//! itself is never rewritten). //! -//! The URL may hold the Store's password: [`PostgresUrl`] has no `Debug`, -//! and nothing here puts any part of the URL into a message. +//! The client is tokio-postgres 0.7 (`Config::from_str`, its `UrlParser`): +//! the userinfo ends at the first `@` anywhere in the URL; the host list +//! ends at the first `/` or `?` after it and splits at each `,`; a host is +//! what a `[...]` holds, else what comes before its first `:`; each host, +//! each query key and a `hostaddr` value are percent-decoded (`%` and two +//! hex digits, any other `%` kept), and a host whose decoded bytes start +//! with `/` is a Unix socket directory. A host is then dialled through +//! `getaddrinfo`, which also reads the legacy IPv4 forms of `inet_aton` +//! (`127.1`, `2130706433`, `0x7f.1`, `017700000001`) and IPv6 zone ids +//! (`::1%lo`); [`ip`] reads both. +//! +//! The URL may hold the Store's password: nothing here keeps it or puts any +//! part of the URL into a message. +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// A URL as `scheme://[userinfo@]host[:port][/path][?query]`, borrowed. -pub struct PostgresUrl<'a> { - scheme: &'a str, - /// Everything before the last `@` of the authority, password included. - userinfo: Option<&'a str>, - /// The host, without an IPv6 address's brackets. - host: &'a str, - /// `:`, or empty. - port: &'a str, - /// The path and query, from the first `/` or `?` on. - tail: &'a str, +/// Every server host `url` names, decoded as its client decodes them: each +/// host of its host list, then each one a `host` or `hostaddr` query +/// parameter names, in order. A `host` value the client takes as one host +/// is split at `,` here too, so no spelling of it goes unchecked. A URL +/// naming none names the client's default, a Unix socket (`""`). +/// `None` when `url` is not one the client reads: no `postgres://` or +/// `postgresql://`, a `[` never closed, anything but `:port` after its +/// `]`, a parameter with no `=`, or a host, key or `hostaddr` value whose +/// decoded bytes are not UTF-8 (a socket directory may be any bytes). +pub fn url_hosts(url: &str) -> Option> { + let rest = (url.strip_prefix("postgres://")).or_else(|| url.strip_prefix("postgresql://"))?; + // the userinfo ends at the first `@`, wherever it is + let rest = rest.split_once('@').map_or(rest, |(_, after)| after); + let end = rest.find(['/', '?']).unwrap_or(rest.len()); + let (list, tail) = rest.split_at(end); + let mut hosts = Vec::new(); + if !list.is_empty() { + for chunk in list.split(',') { + let host = match chunk.strip_prefix('[') { + Some(v6) => { + let (host, after) = v6.split_once(']')?; + if !after.is_empty() && !after.starts_with(':') { + return None; + } + host + } + None => chunk.split(':').next().unwrap_or(chunk), + }; + hosts.push(host_text(host)?); + } + } + // the path, if any, ends at the first `?`; then `key=value` pairs, each + // key ending at its first `=`, each value at the next `&` + let mut query = tail.split_once('?').map_or("", |(_, query)| query); + while !query.is_empty() { + let (key, after) = query.split_once('=')?; + let (value, next) = after.split_once('&').unwrap_or((after, "")); + query = next; + match String::from_utf8(decode(key)).ok()?.as_str() { + "host" => match host_text(value)? { + path if path.starts_with('/') => hosts.push(path), + named => hosts.extend(named.split(',').map(str::to_owned)), + }, + "hostaddr" => { + let value = String::from_utf8(decode(value)).ok()?; + hosts.extend(value.split(',').map(str::to_owned)); + } + _ => {} + } + } + if hosts.is_empty() { + hosts.push(String::new()); + } + Some(hosts) } -impl<'a> PostgresUrl<'a> { - /// Splits `url`; `None` when it has no `://`, an unclosed `[`, or a - /// port that is not 1 to 5 digits (a host list `h1,h2:5433` reads as - /// one host holding a `,`). - pub fn parse(url: &'a str) -> Option { - let (scheme, rest) = url.split_once("://")?; - let end = rest.find(['/', '?']).unwrap_or(rest.len()); - let (authority, tail) = rest.split_at(end); - let (userinfo, host_port) = match authority.rsplit_once('@') { - Some((userinfo, host_port)) => (Some(userinfo), host_port), - None => (None, authority), - }; - let (host, port) = match host_port.strip_prefix('[') { - Some(v6) => v6.split_once(']')?, - None => match host_port.rsplit_once(':') { - Some((host, _)) => (host, &host_port[host.len()..]), - None => (host_port, ""), - }, - }; - let port_ok = match port.strip_prefix(':') { - Some(digits) => { - (1..=5).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit()) +/// One host as the client reads it: percent-decoded; a socket directory +/// (decoded bytes starting with `/`) may be any bytes, any other host must +/// be UTF-8. +fn host_text(raw: &str) -> Option { + let bytes = decode(raw); + match bytes.first() { + Some(b'/') => Some(String::from_utf8_lossy(&bytes).into_owned()), + _ => String::from_utf8(bytes).ok(), + } +} + +/// `text` percent-decoded as the `percent-encoding` crate decodes it: `%` +/// and two hex digits (either case) is that byte, any other `%` is kept. +fn decode(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut at = 0; + while at < bytes.len() { + let byte = bytes[at]; + let hex = |at: usize| bytes.get(at).and_then(|b| (*b as char).to_digit(16)); + match (byte, hex(at + 1), hex(at + 2)) { + (b'%', Some(high), Some(low)) => { + decoded.push((high * 16 + low) as u8); + at += 3; + } + _ => { + decoded.push(byte); + at += 1; } - None => port.is_empty(), - }; - if !port_ok { - return None; } - Some(Self { - scheme, - userinfo, - host, - port, - tail, - }) } + decoded +} - /// The host, without an IPv6 address's brackets. - pub fn host(&self) -> &'a str { - self.host +/// Whether `host` (one of [`url_hosts`]) names a Unix socket: none (the +/// client's default), or a path. +pub fn socket(host: &str) -> bool { + host.is_empty() || host.starts_with('/') || host.starts_with('@') +} + +/// Whether `host` (one of [`url_hosts`]) names this host's loopback +/// without being resolved: `localhost` (any case, with or without its +/// final dot), any address of 127.0.0.0/8 or the unspecified address +/// `0.0.0.0` (which reaches this host), `::1` or `::`, or an IPv4-mapped +/// one of those, in any spelling [`ip`] reads. Any other name is not +/// resolved here: one resolving to a loopback address fails at its dial. +pub fn loopback(host: &str) -> bool { + if bare(host).eq_ignore_ascii_case("localhost") { + return true; + } + let local = |v4: Ipv4Addr| v4.is_loopback() || v4.is_unspecified(); + match ip(host) { + Some(IpAddr::V4(v4)) => local(v4), + Some(IpAddr::V6(v6)) => { + v6.is_loopback() || v6.is_unspecified() || v6.to_ipv4_mapped().is_some_and(local) + } + None => false, } +} - /// Whether the host is this host's loopback: `localhost`, `127.0.0.1` - /// or `::1`. - pub fn loopback(&self) -> bool { - matches!(self.host, "127.0.0.1" | "localhost" | "::1") +/// The address `host` spells, if it spells one, as the machine's +/// `getaddrinfo` reads it before it resolves anything: an IPv6 address +/// (brackets and a zone id `%` dropped), or an IPv4 address in any +/// form `inet_aton` accepts. A final dot is dropped first. +pub fn ip(host: &str) -> Option { + let host = bare(host); + if let Ok(v6) = host.parse::() { + return Some(IpAddr::V6(v6)); } + inet_aton(host).map(IpAddr::V4) +} + +/// `host` without the brackets of an IPv6 address, its zone id and a +/// final dot. +fn bare(host: &str) -> &str { + let host = (host.strip_prefix('[').and_then(|h| h.strip_suffix(']'))).unwrap_or(host); + let host = host.split('%').next().unwrap_or(host); + host.strip_suffix('.').unwrap_or(host) +} - /// The values of the query parameter `key`, in order (not - /// percent-decoded). - pub fn query(&self, key: &'a str) -> impl Iterator + 'a { - let query = self.tail.split_once('?').map_or("", |(_, query)| query); - query.split('&').filter_map(move |pair| { - let (name, value) = pair.split_once('=').unwrap_or((pair, "")); - (name == key).then_some(value) - }) +/// `text` as `inet_aton` reads it (glibc's and musl's, which agree but for +/// one leniency kept here: glibc reads a bare `0x` as zero): one to four +/// numbers separated by `.`, each decimal, octal (a leading `0`) or hex +/// (`0x`), each starting with a digit; the last fills the bits the earlier +/// ones leave (`a`, `a.b` with `b` < 2^24, `a.b.c` with `c` < 2^16, +/// `a.b.c.d`), every earlier one a byte. +fn inet_aton(text: &str) -> Option { + let mut parts = Vec::with_capacity(4); + for part in text.split('.') { + if parts.len() == 4 { + return None; + } + parts.push(number(part)?); + } + let (last, earlier) = parts.split_last()?; + if earlier.iter().any(|byte| *byte > 0xff) { + return None; + } + let bits = 8 * (4 - earlier.len() as u32); + if (bits < 32 && *last >> bits != 0) || *last > u64::from(u32::MAX) { + return None; } + let high = earlier.iter().fold(0u64, |value, byte| (value << 8) | byte); + let value = (high << bits) | last; + Some(Ipv4Addr::from(u32::try_from(value).ok()?)) +} - /// The same URL with `host` in place of its host; everything else, - /// the userinfo included, is kept byte for byte. - pub fn with_host(&self, host: &str) -> String { - let user = self.userinfo.map(|u| format!("{u}@")).unwrap_or_default(); - let host = if host.contains(':') { - format!("[{host}]") - } else { - host.to_owned() - }; - format!("{}://{user}{host}{}{}", self.scheme, self.port, self.tail) +/// One number of an `inet_aton` address: decimal, octal after a leading +/// `0`, hex after `0x` or `0X`; `None` when it does not start with a digit, +/// holds another character or overflows. +fn number(part: &str) -> Option { + if !part.as_bytes().first()?.is_ascii_digit() { + return None; + } + let (digits, radix) = match part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) { + Some(hex) => (hex, 16), + None if part.len() > 1 && part.starts_with('0') => (&part[1..], 8), + None => (part, 10), + }; + if digits.is_empty() { + return Some(0); + } + if !digits.chars().all(|c| c.is_digit(radix)) { + return None; } + u64::from_str_radix(digits, radix).ok() } diff --git a/control/crates/layerfs-sandbox-backend/tests/namespaces_protocol.rs b/control/crates/layerfs-sandbox-backend/tests/namespaces_protocol.rs index a59def3c1b..b05d25c0aa 100644 --- a/control/crates/layerfs-sandbox-backend/tests/namespaces_protocol.rs +++ b/control/crates/layerfs-sandbox-backend/tests/namespaces_protocol.rs @@ -3,6 +3,7 @@ //! records from another. Nothing here starts a process. use layerfs_sandbox_backend::{ Bind, HelperSpec, Image, LocalRecord, NamespaceRecord, RuntimeError, SandboxRecord, + RESOLVER_FILES, }; use std::path::{Path, PathBuf}; @@ -28,6 +29,41 @@ fn spec() -> HelperSpec { } } +/// The launcher's resolver files are bound over the root's `/etc` only: +/// never inside the Sandbox directory, under which every Workspace is +/// mounted (and which a diff or a Commit reads), nor inside a bind. A spec +/// whose Sandbox directory or bind would hold one is refused, so the init +/// stage starts no Sandbox where a resolver file could enter a Workspace. +#[test] +fn resolver_files_land_on_the_root_s_etc_never_in_a_workspace() { + let spec = spec(); + let targets = spec.resolver_targets().unwrap(); + assert_eq!( + targets, + [ + PathBuf::from("/etc/resolv.conf"), + PathBuf::from("/etc/hosts") + ] + ); + assert_eq!(RESOLVER_FILES.len(), targets.len()); + let workspaces = spec.sandbox.join("workspaces"); + for target in &targets { + assert!(target.starts_with("/etc"), "{}", target.display()); + assert!(!target.starts_with(&spec.sandbox), "{}", target.display()); + assert!(!target.starts_with(&workspaces), "{}", target.display()); + assert!(!workspaces.starts_with(target), "{}", target.display()); + } + for sandbox in ["/etc", "/"] { + let mut clash = spec.clone(); + clash.sandbox = PathBuf::from(sandbox); + let refusal = clash.resolver_targets().unwrap_err(); + assert!(refusal.contains("which the Sandbox mounts"), "{refusal}"); + } + let mut clash = spec.clone(); + clash.binds = vec![Bind::store(Path::new("/etc/store.sqlite")).unwrap()]; + assert!(clash.resolver_targets().is_err()); +} + #[test] fn the_init_spec_roundtrips() { let spec = spec(); diff --git a/control/crates/layerfs-sandbox/src/direct.rs b/control/crates/layerfs-sandbox/src/direct.rs index a91a24160b..5b04abc7ee 100644 --- a/control/crates/layerfs-sandbox/src/direct.rs +++ b/control/crates/layerfs-sandbox/src/direct.rs @@ -305,6 +305,7 @@ pub fn host(home: &Path, record: &SandboxRecord, target: &Target, message: Messa postgresql: None, message, started: None, + reach_hint: None, } } diff --git a/control/crates/layerfs-sandbox/src/force.rs b/control/crates/layerfs-sandbox/src/force.rs index b9f237122e..0a690672e8 100644 --- a/control/crates/layerfs-sandbox/src/force.rs +++ b/control/crates/layerfs-sandbox/src/force.rs @@ -29,6 +29,7 @@ pub fn native_host(home: &Path, sandbox: &str) -> Result { postgresql: None, message: Message::Absent, started: None, + reach_hint: None, }) } diff --git a/control/crates/layerfs-sandbox/src/host/call.rs b/control/crates/layerfs-sandbox/src/host/call.rs index 46b76e3c7f..8faba10c82 100644 --- a/control/crates/layerfs-sandbox/src/host/call.rs +++ b/control/crates/layerfs-sandbox/src/host/call.rs @@ -71,6 +71,39 @@ impl Op { pub fn asks_daemon_only(self) -> bool { matches!(self, Self::ListWorkspaces | Self::Capacity) } + + /// What it does with a PostgreSQL Store's URL on the side that runs it. + /// A create starts a daemon that dials it (after the reach check), a + /// Commit reads its Branch's head and `expected` there and a status its + /// head: [`StoreUrl::Dialled`]. A close dials it only to end the mount + /// intents a forced unmount left, which it reports when it cannot: + /// [`StoreUrl::Cleanup`]. Every other operation asks only the + /// Sandbox's daemon, which dials the URL its create gave it: + /// [`StoreUrl::Unused`]. + pub fn store_url(self) -> StoreUrl { + match self { + Self::SandboxCreate | Self::Commit | Self::Status => StoreUrl::Dialled, + Self::SandboxClose => StoreUrl::Cleanup, + Self::ListWorkspaces + | Self::Capacity + | Self::Mount + | Self::Exec + | Self::ExecCancel + | Self::Unmount => StoreUrl::Unused, + } + } +} + +/// What a host operation does with a PostgreSQL Store's URL ([`Op::store_url`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StoreUrl { + /// Dialled for its answer: a URL the machine cannot dial refuses it. + Dialled, + /// Dialled for a cleanup it reports when it cannot: the operation runs + /// without a URL the machine cannot dial. + Cleanup, + /// Never dialled: the operation runs without it. + Unused, } /// A Commit `message` as a request carries it. The untyped request checked @@ -267,6 +300,10 @@ pub struct Host { /// command started (`{ exec_started: { stop } }`): the caller that keeps /// its record records the stop handle then (layerfs-project#113). pub started: Option>, + /// What a create's daemon adds when it cannot connect to its + /// PostgreSQL Store's server (`layerfs_machine::platform::loopback_hint`, + /// from the caller), never written. + pub reach_hint: Option, } impl Host { diff --git a/control/crates/layerfs-sandbox/src/host/mod.rs b/control/crates/layerfs-sandbox/src/host/mod.rs index d42f355aaa..7e34338d51 100644 --- a/control/crates/layerfs-sandbox/src/host/mod.rs +++ b/control/crates/layerfs-sandbox/src/host/mod.rs @@ -4,5 +4,5 @@ mod call; mod frame; -pub use call::{Call, Deploy, Host, Message, Op, Started, OPS}; +pub use call::{Call, Deploy, Host, Message, Op, Started, StoreUrl, OPS}; pub use frame::{decode, encode, Sent}; diff --git a/control/crates/layerfs-sandbox/src/launch/local.rs b/control/crates/layerfs-sandbox/src/launch/local.rs index 9a0f55ac51..5cf434d9b2 100644 --- a/control/crates/layerfs-sandbox/src/launch/local.rs +++ b/control/crates/layerfs-sandbox/src/launch/local.rs @@ -148,8 +148,8 @@ fn start_named( 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()) + layerfs_sandbox_backend::url_hosts(url) + .map(|hosts| hosts.join(",")) .unwrap_or_default(), ), DaemonStore::Sqlite { .. } => None, @@ -180,13 +180,7 @@ fn start_named( 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, - ) - }); + .map(|pg_host| (pg_host, host.store.as_str(), host.reach_hint.as_deref())); abandon( id, format!( @@ -446,7 +440,10 @@ pub fn owned(host: &Host, id: &str, own: &Path) -> Result<(), SdkRefusal> { /// daemon's last log lines are read once (the message quotes the last one, /// the detail's `log` keeps them all), then it is stopped and its /// directory deleted, each once (`Failed`). If that cleanup fails, the -/// outcome is `Unknown`, saying what is left. The detail's `daemon` is the +/// outcome is `Unknown`, saying what is left. A daemon that made no +/// connection to its PostgreSQL Store's server (`pg`: the hosts it dials, +/// the Store and the caller's loopback hint) is `Unavailable`, naming them +/// and adding the hint when there is one. The detail's `daemon` is the /// program that was started, which the call layer compares with this /// build's. fn abandon( @@ -454,7 +451,7 @@ fn abandon( mut cause: String, sandbox: Option>, daemon: &Path, - pg: Option<(&str, &str, bool)>, + pg: Option<(&str, &str, Option<&str>)>, ) -> SdkRefusal { let container = sandbox.as_ref().map(|s| s.identity().to_string()); let mut log = None; @@ -487,25 +484,7 @@ fn abandon( || 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, true, Some(pg)) => ("Unavailable", unreached(id, pg), container.is_some()), (None, _, _) => ("Failed", cause, container.is_some()), (Some(left), _, _) => ( "Unknown", @@ -524,3 +503,44 @@ fn abandon( ]), } } + +/// Why Sandbox `id` did not start when its daemon made no connection to +/// its PostgreSQL Store's server (the daemon's own words, from a dial no +/// server answered): the hosts it dials and the Store, with the caller's +/// loopback hint when it has one (a name there may be a loopback address +/// the machine does not share). +fn unreached(id: &str, (pg_host, store, hint): (&str, &str, Option<&str>)) -> String { + let at = match pg_host { + "" => String::new(), + host => format!(" at {host}"), + }; + let message = format!( + "Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store}'s server{at}" + ); + match hint { + Some(hint) => format!("{message}; {hint}"), + None => message, + } +} + +#[cfg(test)] +mod tests { + /// A daemon that made no connection says so, naming the hosts it dials, + /// and adds the caller's loopback hint only when the caller gave one. + #[test] + fn a_daemon_that_made_no_connection_carries_the_caller_s_hint() { + let hint = "if its host is a loopback address on the lima machine dev (a hosts entry can make a name one), the machine does not share this host's loopback; give the Store a host the machine reaches (host.lima.internal), or give the machine its own URL with `layerfs store connect pg --machine dev`"; + let with = super::unreached("s1", ("db.example", "pg", Some(hint))); + assert_eq!( + with, + format!("Sandbox s1 did not start: its daemon cannot reach PostgreSQL Store pg's server at db.example; {hint}") + ); + let without = super::unreached("s1", ("10.0.0.5", "pg", None)); + assert_eq!( + without, + "Sandbox s1 did not start: its daemon cannot reach PostgreSQL Store pg's server at 10.0.0.5" + ); + let socket = super::unreached("s1", ("", "pg", None)); + assert!(socket.ends_with("Store pg's server"), "{socket}"); + } +} diff --git a/control/crates/layerfs-sandbox/src/lifecycle.rs b/control/crates/layerfs-sandbox/src/lifecycle.rs index 733485a547..f8cb158041 100644 --- a/control/crates/layerfs-sandbox/src/lifecycle.rs +++ b/control/crates/layerfs-sandbox/src/lifecycle.rs @@ -385,7 +385,16 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { .map_err(values::wire)?; owner.stop(STOP_S).map_err(values::wire)?; owner.delete().map_err(values::wire)?; - let left = crate::mount_intents::end(Ok(&host.open_args()), &bound); + // a PostgreSQL Store's URL that was not resolved for the close (one + // the machine cannot dial, `route`): what it left is reported + let pg = (host.store_record.as_ref()) + .is_some_and(|r| r.kind().ok() == Some(layerfs_store::record::StoreKind::Postgresql)); + let open = host.open_args(); + let open = match (pg, &host.postgresql) { + (true, None) => Err("no URL of the PostgreSQL Store this machine can dial was resolved"), + _ => Ok(&open), + }; + let left = crate::mount_intents::end(open, &bound); lock(&SANDBOXES)?.remove(&directory); std::fs::remove_dir_all(&directory).map_err(failed)?; layerfs_home::home::generation::moved_above(&directory); diff --git a/control/crates/layerfs-sandbox/src/route.rs b/control/crates/layerfs-sandbox/src/route.rs index 0d0f1707bb..54a81cb1f6 100644 --- a/control/crates/layerfs-sandbox/src/route.rs +++ b/control/crates/layerfs-sandbox/src/route.rs @@ -4,7 +4,7 @@ //! layerfs-project#108), and spooled output streamed back as events. use super::deploy::{self, Side}; use super::record::SandboxRecord; -use crate::host::{Call, Deploy, Host, Message, Op, Sent}; +use crate::host::{Call, Deploy, Host, Message, Op, Sent, StoreUrl}; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::events::Events; use layerfs_home::home::{self, paths}; @@ -75,6 +75,7 @@ fn host_args( postgresql, message, started: None, + reach_hint: None, }) } @@ -89,18 +90,22 @@ enum RunRoot { /// A PostgreSQL Store's `postgresql` argument for a Sandbox on `machine` /// (#535 §7.4): the URL the machine's own connection names, else the record's, -/// with its password, resolved here in the caller, with a loopback host -/// rewritten to the machine's alias or refused -/// (`layerfs_machine::platform::reach`). It travels only in the one request that runs -/// the call and is never written to a record. -/// With it, what a failed reach check tells a user to check on that -/// machine's platform, if anything. `store.update` and `store.status` build their check's -/// argument here too. +/// with its password, resolved here in the caller and dialled as it is: a +/// loopback host the machine does not share is refused, nothing is +/// rewritten and no machine is asked (`layerfs_machine::platform::reach`). +/// It travels only in the one request that runs the call and is never +/// written to a record. +/// With it, what a dial from that machine that made no connection adds +/// when the machine does not share this host's loopback and the URL names +/// a host by name (`layerfs_machine::platform::loopback_hint`): a name +/// resolving to a loopback address there fails its one dial, never +/// resolved here to be refused up front. `store.update` and `store.status` +/// build their check's argument here too. pub fn reached( home: &Path, machine: &str, record: &StoreRecord, -) -> Result<(PgSelection, Option<&'static str>)> { +) -> Result<(PgSelection, Option)> { let url = layerfs_store::record::url_on(record, machine)?; // a build without machines (the guest's) runs its own Sandboxes on the // machine it is, which shares its loopback @@ -108,10 +113,9 @@ pub fn reached( let (url, hint) = { let spec = layerfs_machine::machine_spec(home, &layerfs_machine::machine_of(home, machine)?)?; - let hint = (spec.kind == layerfs_machine::platform::Platform::AppleContainer).then_some( - "an apple-container machine reaches a server on this host only when it listens on the container network's bridge (0.0.0.0, as Docker Desktop publishes a port), not on 127.0.0.1 alone", - ); - let url = layerfs_machine::platform::reach(&spec, &url) + let store = record.name(); + let hint = layerfs_machine::platform::loopback_hint(&spec, store, &url); + let url = layerfs_machine::platform::reach(&spec, store, &url) .map_err(layerfs_machine::machine_refusal)?; (url, hint) }; @@ -131,9 +135,11 @@ pub fn reached( /// process's held host session for the Store at `key`, #65) reads the /// LayerFS schema's binding, which must be the Store record's, and finds /// `project` there. It proves the server is reached and is the same Store; -/// a failure names the machine and the host it tried, never the URL, and -/// adds `hint`. A build without the PostgreSQL engine says so, not that it -/// cannot reach. A project the schema does not hold is `NoSuchProject`. +/// a failure names the machine and the hosts it tried, never the URL, and +/// adds `hint` when no connection was made (not when the server answered, +/// a refused login say). A build without the PostgreSQL engine says so, +/// not that it cannot reach. A project the schema does not hold is +/// `NoSuchProject`. fn reach_check( who: &str, (store, key, project): (&StoreRecord, &Path, &str), @@ -141,8 +147,8 @@ fn reach_check( hint: Option<&str>, ) -> Result<()> { let url = postgresql.url.as_deref().unwrap_or(""); - let host = layerfs_sandbox_backend::PostgresUrl::parse(url) - .map(|url| url.host().to_owned()) + let host = layerfs_sandbox_backend::url_hosts(url) + .map(|hosts| hosts.join(",")) .unwrap_or_default(); let reached = layerfs_store::postgresql::reader::reach(key, store, postgresql, project) .map_err(|refusal| { @@ -157,8 +163,12 @@ fn reach_check( ), ) } - (_, Some(hint)) => format!("{}; {hint}", refusal.message), - (_, None) => refusal.message, + (_, Some(hint)) + if layerfs_store::postgresql::open::not_connected(&refusal.message) => + { + format!("{}; {hint}", refusal.message) + } + _ => refusal.message, }; refused( "Unavailable", @@ -304,12 +314,22 @@ fn host_op( .map(str::to_owned), }; let kind = target.store_ref.kind(); - let (postgresql, hint) = match kind { - StoreKind::Postgresql => { + // a PostgreSQL Store's URL is resolved (and a URL the machine cannot + // dial refused) only for an operation that dials it; a close runs + // without one, reporting the mount intents it then cannot end, so a + // Sandbox can always be read and removed + let (postgresql, hint) = match (kind, op.store_url()) { + (StoreKind::Postgresql, StoreUrl::Dialled) => { let (value, hint) = reached(&home, machine, &target.record)?; (Some(value), hint) } - StoreKind::Sqlite => (None, None), + (StoreKind::Postgresql, StoreUrl::Cleanup) => { + match reached(&home, machine, &target.record) { + Ok((value, hint)) => (Some(value), hint), + Err(_) => (None, None), + } + } + _ => (None, None), }; // a Sandbox's host operations run where its machine runs them, for // either Store kind (#535 §7.4) @@ -362,10 +382,10 @@ fn host_op( &format!("machine {machine}"), (&target.record, &key, &target.project), postgresql, - hint, + hint.as_deref(), )?; } - let held = postgresql.is_some(); + let held = kind == StoreKind::Postgresql; let how = deploy::resolve(&Side::Home(&home), &choice)?; // `sandbox.get`'s reads ask only the Sandbox's daemon // (layerfs-project#181): no run root is made, no Store lease @@ -382,14 +402,17 @@ fn host_op( )?; return local(host, call); } - let host = host_args( - &home, - (&target.store, &target.project, &target.record), - (kind, postgresql), - how, - (sandbox, message), - RunRoot::Made, - )?; + let host = Host { + reach_hint: hint, + ..host_args( + &home, + (&target.store, &target.project, &target.record), + (kind, postgresql), + how, + (sandbox, message), + RunRoot::Made, + )? + }; // the host code reads the project's Branches through its open // Store, which this process leases. A PostgreSQL Store opens no // Store service (#65): the lease covers this call, and a read @@ -432,7 +455,7 @@ fn host_op( project_record, choice, machine: postgresql.as_ref().map(|_| machine.to_owned()), - reach_hint: postgresql.as_ref().and(hint).map(str::to_owned), + reach_hint: postgresql.as_ref().and(hint), postgresql, }; let request = crate::host::encode(&sent)?; @@ -526,15 +549,16 @@ pub fn in_worker( } layerfs_home::trace::step("records"); let how = deploy::resolve(&Side::Worker(root), &choice)?; - let postgresql = match kind { - StoreKind::Postgresql => Some(postgresql.ok_or_else(|| { - refused( - "InvalidInput", - "a PostgreSQL Sandbox call carries its server's resolved postgresql value", - ) - })?), - StoreKind::Sqlite => None, - }; + // the operations that dial a PostgreSQL Store's URL carry it; the + // others carry none, or one for a close's cleanup ([`Op::store_url`]) + if kind == StoreKind::Postgresql && op.store_url() == StoreUrl::Dialled && postgresql.is_none() + { + return Err(refused( + "InvalidInput", + "a PostgreSQL Sandbox call carries its server's resolved postgresql value", + )); + } + let postgresql = postgresql.filter(|_| kind == StoreKind::Postgresql); let key = store_path(root, store, &record, kind); if let (Some(postgresql), Op::SandboxCreate) = (&postgresql, op) { let who = match &machine { @@ -548,15 +572,18 @@ pub fn in_worker( reach_hint.as_deref(), )?; } - let held = postgresql.is_some(); - let host = host_args( - root, - (store, project, &record), - (kind, postgresql), - how, - (sandbox, message), - RunRoot::Made, - )?; + let held = kind == StoreKind::Postgresql; + let host = Host { + reach_hint, + ..host_args( + root, + (store, project, &record), + (kind, postgresql), + how, + (sandbox, message), + RunRoot::Made, + )? + }; layerfs_home::trace::step("host_args"); // a PostgreSQL Store opens no Store service here (#65); its reads run // on the held read session diff --git a/control/crates/layerfs-sandbox/tests/capacity_read.rs b/control/crates/layerfs-sandbox/tests/capacity_read.rs index e9c768b3c9..d88d997105 100644 --- a/control/crates/layerfs-sandbox/tests/capacity_read.rs +++ b/control/crates/layerfs-sandbox/tests/capacity_read.rs @@ -314,6 +314,7 @@ fn the_worker_s_side_reads_the_capacity_model() { postgresql: None, message: Message::Absent, started: None, + reach_hint: None, }; let answer = layerfs_sandbox::dispatch::call(host, HostCall::Capacity); // the call left its Sandbox live in this process's table: it goes, diff --git a/control/crates/layerfs-sandbox/tests/installed_repair.rs b/control/crates/layerfs-sandbox/tests/installed_repair.rs index 939cd443fe..576ec8bbf2 100644 --- a/control/crates/layerfs-sandbox/tests/installed_repair.rs +++ b/control/crates/layerfs-sandbox/tests/installed_repair.rs @@ -80,6 +80,7 @@ fn sandbox_create_repairs_an_incomplete_sqlite_project_record() { postgresql: None, message: Message::Absent, started: None, + reach_hint: None, }; // the repair happens before launch; a host that can launch a daemon // starts one, which is removed again diff --git a/control/crates/layerfs-sandbox/tests/retired_docker.rs b/control/crates/layerfs-sandbox/tests/retired_docker.rs index 075702b11c..d94cf3a38c 100644 --- a/control/crates/layerfs-sandbox/tests/retired_docker.rs +++ b/control/crates/layerfs-sandbox/tests/retired_docker.rs @@ -59,6 +59,7 @@ fn host(root: &Path) -> Host { postgresql: None, message: Message::Absent, started: None, + reach_hint: None, } } diff --git a/control/crates/layerfs-store/src/postgresql/open.rs b/control/crates/layerfs-store/src/postgresql/open.rs index dcf1c50df2..fb5cb85dd1 100644 --- a/control/crates/layerfs-store/src/postgresql/open.rs +++ b/control/crates/layerfs-store/src/postgresql/open.rs @@ -114,13 +114,35 @@ pub fn no_session(error: &layerfs_storage::port::PersistenceError) -> Option "no connection to the server was made (it refused the connection, did not answer, or closed it)", + "Closed" => NO_CONNECTION, "Rejected" => "the server refused the session: the database does not exist, or the user or password is wrong", _ => return None, }; Some(refused("Unavailable", message)) } +/// How [`no_session`] says that no connection was made. +const NO_CONNECTION: &str = "no connection to the server was made (it refused the connection, did not answer, or closed it)"; + +/// Whether a PostgreSQL refusal's `message` says that no connection to +/// the server was made at all: the name did not resolve, nothing listened +/// or nothing answered in time (the client's `error connecting to server` +/// and `timeout waiting for server`, a silent dial's limit, or +/// [`no_session`]'s words). A server that answered (a refused login, a +/// missing database, any other error it sent) was reached: `false`. The +/// one case where a machine's loopback hint can help. +pub fn not_connected(message: &str) -> bool { + [ + NO_CONNECTION, + "error connecting to server", + "timeout waiting for server", + "the server did not answer within", + "the dial could not be started", + ] + .iter() + .any(|said| message.contains(said)) +} + /// The binding key the LayerFS schema `schema` records. fn binding(url: &str, schema: &str, sync: &str) -> Result, SdkRefusal> { (layerfs_persistence::PostgresHandles::binding(&selection(url, schema, sync))).map_err( diff --git a/control/crates/layerfs-store/tests/observed_reach.rs b/control/crates/layerfs-store/tests/observed_reach.rs index 54a3219a99..211c2f4e40 100644 --- a/control/crates/layerfs-store/tests/observed_reach.rs +++ b/control/crates/layerfs-store/tests/observed_reach.rs @@ -5,7 +5,9 @@ //! machine's entry is forgotten; `connections` lists every side that //! connects; an old record reads `outdated` and a clean write drops its old //! fields; a missing login reads `missing`; `store auths` lists a login -//! file it cannot read as a broken row. +//! file it cannot read as a broken row. A failed check is `not_connected` +//! (the one case a machine's loopback hint is added) only when no server +//! answered. use layerfs_bridge::control::SdkValue; use layerfs_home::home::{self, observed, paths, write_entity}; use layerfs_home::state::{Reason, State}; @@ -314,3 +316,58 @@ fn a_login_file_that_cannot_be_read_is_a_broken_row() { ); std::fs::remove_dir_all(home).unwrap(); } + +/// The words of a check that failed `url`. +fn failed_check(url: &str) -> String { + match layerfs_persistence::postgresql_access(url, "layerfs") { + Ok(_) => panic!("the check of {url} passed"), + Err(error) => error.to_string(), + } +} + +/// `not_connected` holds for what a dial no server answered says: nothing +/// listening, a name that does not resolve, the session's own words for +/// both. A server that answered (a missing database, a setting it refused) +/// was reached, so no loopback hint applies. +#[test] +fn only_a_dial_no_server_answered_is_not_connected() { + use layerfs_store::postgresql::open::not_connected; + let refused = failed_check("postgres://lfs@127.0.0.1:1/db?connect_timeout=5"); + assert!(not_connected(&refused), "{refused}"); + let unresolved = + failed_check("postgres://lfs@layerfs-no-such-host.invalid/db?connect_timeout=5"); + assert!(not_connected(&unresolved), "{unresolved}"); + assert!(not_connected( + "no connection to the server was made (it refused the connection, did not answer, or closed it)" + )); + assert!(!not_connected( + "the server refused the session: the database does not exist, or the user or password is wrong" + )); + let Some(url) = std::env::var("LAYERFS_TEST_POSTGRES_URL").ok() else { + eprintln!("NOT_RUN (server half): LAYERFS_TEST_POSTGRES_URL is unset"); + return; + }; + // the test URL is a postgres:// URL or key=value words + let (setting, database) = match url.split_once("://") { + Some(_) => { + let and = if url.contains('?') { "&" } else { "?" }; + ( + format!("{url}{and}options=-c%20no_such_setting%3D1"), + format!("{url}{and}dbname=layerfs_no_such_db"), + ) + } + None => ( + format!("{url} options='-c no_such_setting=1'"), + format!("{url} dbname=layerfs_no_such_db"), + ), + }; + for answered in [ + // a setting the server refuses at login + failed_check(&setting), + // a database the server does not hold + failed_check(&database), + ] { + assert!(answered.contains("db error"), "{answered}"); + assert!(!not_connected(&answered), "{answered}"); + } +} diff --git a/control/crates/layerfs-store/tests/postgresql_no_auth.rs b/control/crates/layerfs-store/tests/postgresql_no_auth.rs index 84a65e98cf..17b229527b 100644 --- a/control/crates/layerfs-store/tests/postgresql_no_auth.rs +++ b/control/crates/layerfs-store/tests/postgresql_no_auth.rs @@ -103,3 +103,35 @@ fn a_saved_login_goes_into_the_dialled_url() { ); std::fs::remove_dir_all(home).unwrap(); } + +/// Every URL a machine's Sandbox dials (`url_on`, which the route's reach +/// check reads) is a `postgres://` or `postgresql://` URL: libpq's +/// key=value words, as a Store's address or a machine's own, are refused +/// `InvalidInput` when the login is put in, before anything reads or dials +/// them. +#[test] +fn a_key_value_address_is_refused_before_anything_dials_it() { + let home = std::env::temp_dir().join(format!("layerfs-pg-words-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + layerfs_home::home::ensure(&home).unwrap(); + layerfs_store::postgresql::login::save(&home, "pg-app", "alice", "s3 cret").unwrap(); + for words in [ + "host=localhost dbname=layerfs_db", + "host=db.example port=5432 dbname=layerfs_db", + ] { + let record = + StoreRecord::connected("pg", words, "layerfs", "local", Some("pg-app")).in_home(&home); + for refusal in [ + url(&record).unwrap_err(), + url_on(&record, "lab").unwrap_err(), + ] { + assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); + assert!( + refusal.message.contains("postgresql:// or postgres://"), + "{}", + refusal.message + ); + } + } + std::fs::remove_dir_all(home).unwrap(); +} diff --git a/core/docs/issues/project-41/gc-t12.3a-sqlite-matrix-report.md b/core/docs/issues/project-41/gc-t12.3a-sqlite-matrix-report.md index 756663c4c8..9fce37944d 100644 --- a/core/docs/issues/project-41/gc-t12.3a-sqlite-matrix-report.md +++ b/core/docs/issues/project-41/gc-t12.3a-sqlite-matrix-report.md @@ -272,7 +272,7 @@ AC-51 does not depend on the projection alone. `sdk_path_removal` (5); and the `layerfs-control project_delete_worker` (14), the `layerfs-store project_delete` (18), `compact_report_status` (6) and the - PostgreSQL AC-44 suite `postgresql_compact` (32 tests; AC-44's nine are + PostgreSQL AC-44 suite `postgresql_compact` (33 tests; AC-44's nine are `a_fully_privileged_role_compacts`, `a_role_without_create_on_the_database_is_refused_as_unsupported`, `a_role_without_create_on_the_store_schema_is_refused_as_unsupported`, diff --git a/docs/architecture/api/sdk/sandbox.md b/docs/architecture/api/sdk/sandbox.md index dee27af379..d20e47af1c 100644 --- a/docs/architecture/api/sdk/sandbox.md +++ b/docs/architecture/api/sdk/sandbox.md @@ -115,8 +115,11 @@ it stopped ``: ``", then "Its daemon's last error: …" from 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` +`` being every host its URL names; on a machine that does not share +this computer's loopback, when that URL names a host by name, it adds the +same advice as the loopback refusal: the platform's name for this computer +or `layerfs store connect --machine `). The +Sandbox resolves names as its machine does. 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`). diff --git a/docs/architecture/control/machines/README.md b/docs/architecture/control/machines/README.md index 530691a4de..5750d76c34 100644 --- a/docs/architecture/control/machines/README.md +++ b/docs/architecture/control/machines/README.md @@ -95,7 +95,7 @@ The per-platform values are in [Platforms](platforms.md). stop(spec) -> () provider_state(spec) -> State no worker or guest contact status(spec) -> Status starts nothing - reach(spec, url) -> String PostgreSQL URL to dial + loopback(spec) -> Loopback Shared, or Apart(this host) forward(spec, guest_port) -> Forward ``` @@ -104,7 +104,7 @@ The per-platform values are in [Platforms](platforms.md). | `create`, `start` | `validate`, `check_bundle`; `start` answers `None` when the route is `InProcess` | the adapter; `create` forwards `spec.state.port` when the caller recorded one (`worker_port`), `start` refuses `InvalidInput` without it on `lima` and `apple-container` | | `stop`, `remove`, `status` | `validate` (`InUse` is the caller's check) | the adapter | | `status_within`, `provider_within` | as `status` | every command killed with its process group at the deadline, answered `Unknown` | -| `reach` | `validate` | no message holds the URL | +| `reach`, `loopback_hint` | `validate` | `reach::dial` with the adapter's `loopback`: the URL as given or a refusal; the hint a dial that made no connection adds on an `Apart` machine when the URL names a host by name; nothing runs and no message holds the URL ([Reach](workers-and-reach.md#reach-reachrs)) | | `forward`, `forward_close` | `validate`; port 0 is `InvalidInput` | the adapter; close ends only a pid whose command line still names the port | | `load_image`, `cached_image` | `validate`; `docker` only | `docker load -i`, answers `sha256:<64 hex>` | | `copy_in`, `copy_out` | `validate`; the platform's `guest` | one `tar` stream in, `cat` out to a new 0600 file | diff --git a/docs/architecture/control/machines/platforms.md b/docs/architecture/control/machines/platforms.md index 1800dbfaa3..f8d3cb50fb 100644 --- a/docs/architecture/control/machines/platforms.md +++ b/docs/architecture/control/machines/platforms.md @@ -102,7 +102,7 @@ volume, not to `docker logs` | a container named `` without the `layerfs.role=machine-worker` label | `Exists` from `start`, `stop` and `provider_within` alike ("… is not a LayerFS worker; it is left alone"); it is never touched | | `guest` | `docker -H unix:// exec` in the worker container | | `load_image` | `docker load -i` (up to 300 s), `sha256:<64 hex>` | -| `reach` | Linux host: as given (host network); Docker Desktop: a loopback host becomes the address the worker resolves `host.docker.internal` to (`getent ahostsv4`) | +| `reach` | Linux host: `Shared` (host network), every URL as given; Docker Desktop: `Apart`, a loopback host or Unix socket refused naming `host.docker.internal`, which the worker and its Sandboxes resolve (Docker Desktop's DNS); nothing is rewritten and no `docker` command runs ([Reach](workers-and-reach.md#reach-reachrs)) | | `forward` | `Unsupported`: Docker publishes a container's ports only at start, so Workspace calls go through the worker | The secret goes into a private tmpfs after start, so it is in no command @@ -148,7 +148,7 @@ named volume. | `stop` | `container stop` (5 s grace) if running; forced: `container stop --time 0`, also when failed or between states | | `remove` | `container delete --force`, then `container volume delete` | | `status` | `container inspect` `status.state`: `running`, `stopped`, `failed`; any other (`stopping`, `unknown`) is `Unavailable`, as lima's and docker's passing states, never recorded `failed` | -| `reach` | a loopback host becomes the recorded gateway, else `status.networks[0].ipv4Gateway` read while it runs | +| `reach` | `Apart`: a loopback host or Unix socket refused naming the gateway the last start recorded (else vmnet's default `192.168.64.1`), on which the server must listen; the guest has no name for this host; no `container` command runs | | `forward` | `Unsupported`: the CLI publishes a port only at create | `/proc/sys` is read-only until remounted; preparation remounts it before @@ -185,7 +185,7 @@ One Lima instance (`vmType: vz`, macOS), made from a template written to | `stop` | `limactl stop` (up to 300 s) if running; forced: `limactl stop --force`, also when `Broken`; instance and disk stay | | `status` | `limactl list` `Running`, `Stopped`, `Broken` (failed); any other is `Unavailable` | | `remove` | `limactl delete --force`, then `limactl disk delete` | -| `reach` | a loopback host becomes `192.168.5.2` (the address of `host.lima.internal`; the Sandbox root has no such hosts entry) | +| `reach` | `Apart`: a loopback host or Unix socket refused naming `host.lima.internal` (the guest's hosts entry for `192.168.5.2`, which its Sandboxes read through the bound resolver files) | | `forward` | a detached `ssh -N -L` over Lima's `ssh.config`, answering its pid ([Workers and reach](workers-and-reach.md#forwards)) | `disk` sizes the data disk only; Lima's root disk keeps Lima's own size. @@ -203,7 +203,7 @@ One Lima instance (`vmType: vz`, macOS), made from a template written to | docker `start` `Failed` | image not in the Engine (`--pull never`), or no published port (macOS) | same | | `missing: host:macos`, `host:apple-silicon`, `tool:container` | not a Mac, not `aarch64`, no `container` CLI | [`apple_container/adapter.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs) | | apple-container `Failed`: "… inspect answer is not the shape this adapter knows" | another CLI version's JSON | [`apple_container/observe.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/observe.rs) | -| apple-container `reach` `Unavailable`: no gateway | the machine is stopped | same | +| `reach` `Unsupported`: "… its URL names this host's loopback (…), which the machine does not share; give the Store a host the machine reaches (…), or give the machine its own URL with `layerfs store connect --machine `" (or "… names no host (a Unix socket of the caller) …") | a loopback or Unix-socket PostgreSQL URL on docker (Docker Desktop), lima or apple-container | [`reach.rs`](../../../../control/crates/layerfs-platform/src/reach.rs) | | apple-container `Unavailable`: "… a transitional or unrecognized state" | the container is `stopping` (or `unknown`); ask again once it settles, or force the stop | same; [`apple_container/power.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/power.rs) | | `missing: host:macos`, `tool:limactl` | not a Mac, no `limactl` | [`lima/observe.rs`](../../../../control/crates/layerfs-platform/src/platforms/lima/observe.rs) | | lima "… is not an ext4 mount" | the data disk did not attach as ext4 | [`lima/power.rs`](../../../../control/crates/layerfs-platform/src/platforms/lima/power.rs) | diff --git a/docs/architecture/control/machines/workers-and-reach.md b/docs/architecture/control/machines/workers-and-reach.md index 073f99aeee..92341534f5 100644 --- a/docs/architecture/control/machines/workers-and-reach.md +++ b/docs/architecture/control/machines/workers-and-reach.md @@ -264,32 +264,47 @@ it in the worker server's files alone and refuses a manifest that enables it. ## Reach (`reach.rs`) -A PostgreSQL Store's URL is written for the caller's host. -`reach(spec, url)` answers the URL that machine's daemon dials; it starts -nothing, and no message holds any part of the URL. +A PostgreSQL Store's URL is the user's configuration: LayerFS dials it +exactly as configured from every machine, rewrites no part of it and reads +no port (owner, 2026-11-24). +`reach(spec, store, url)` answers that URL or refuses it; it starts nothing, +runs no provider command and resolves no name, and no message holds any +part of the URL but a loopback host. Each adapter declares its `Loopback`. ```text - dial(spec, url, loopback) - Shared? ------------------------------------------> url as given - one postgres[ql]://[user@]host[:port]/... ? no --> InvalidInput - ?host= or ?hostaddr= ------------------------ yes --> Unsupported - no host (a Unix socket) --------------------- yes --> Unsupported - host not localhost / 127.0.0.1 / ::1 -------- yes --> url as given - sslmode=verify-full ------------------------- yes --> Unsupported - Alias(a) | Lookup(read) --> with_host(a), every other byte kept + dial(spec, (store, url), adapter.loopback(spec)) + Shared ---------------------------------------------> url as given, unread + Apart(this host): + hosts = url_hosts(url): the host list and host= / hostaddr= parameters, + read as the client reads them (none: the socket) + not a URL the client reads -----------------------> InvalidInput + a host empty, or a path (a Unix socket) ----------> Unsupported + advice + a host is this host's loopback -------------------> Unsupported + advice + else ---------------------------------------------> url as given + advice: "give the Store a host the machine reaches (), or give + the machine its own URL with `layerfs store connect + --machine `", the Store and machine named ``` -| Platform | `Loopback` | A loopback host becomes | +| Platform | `Loopback` | The refusal names | | --- | --- | --- | -| `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 | - -`verify-full` is refused because the rewritten host is not in the server's -certificate: give the Store a URL whose host every machine can verify. -`PostgresUrl` keeps userinfo byte for byte, brackets an IPv6 alias, and has -no `Debug` +| `native` | `Shared` | — | +| `docker` | `Shared` on a Linux host (`--network host`); `Apart` on Docker Desktop | `host.docker.internal` | +| `lima` | `Apart` | `host.lima.internal` (192.168.5.2) | +| `apple-container` | `Apart` | the gateway the last start recorded, else `192.168.64.1`; the server must listen on it, not on 127.0.0.1 alone | + +| Rule | Detail | Source | +| --- | --- | --- | +| Hosts, as the client reads them | The daemon's client is tokio-postgres (`Config::from_str`), and `url_hosts` reads a URL as it does: the userinfo ends at the first `@` anywhere; the host list ends at the first `/` or `?` and splits at each `,` before a host's `[...]` or first `:` is read (`h1:5432,h2`, `h1,[2001:db8::1]` and `[::1]:5432,h2` are valid lists); hosts, query keys and `hostaddr` values are percent-decoded (`%6Cocalhost` is `localhost`, `h%6Fst=` is `host=`); a host decoding to a path is a socket directory. A `host=` value the client takes as one host is split at `,` too, so no part of it goes unchecked. Only `postgres://` and `postgresql://` URLs reach here: a Store's address and a machine's own are refused otherwise when the login is put in (`secrets::parts`); what is not such a URL, or what the client refuses to read (an unclosed `[`, a parameter with no `=`, a host that does not decode to UTF-8), is `InvalidInput` | [`postgres_url.rs`](../../../../control/crates/layerfs-sandbox-backend/src/postgres_url.rs) `url_hosts`; [`secrets.rs`](../../../../control/crates/layerfs-home/src/secrets.rs) `parts` | +| Loopback | `localhost` (any case, with or without its final dot); every address of 127.0.0.0/8 and the unspecified `0.0.0.0`, in every form the machine's `getaddrinfo` reads through `inet_aton` (`127.1`, `2130706433`, `127.000.000.001`, `0x7f.1`, `017700000001`); `::1` and `::` in any spelling, with or without brackets or a zone id (`::1%lo`), and their IPv4-mapped forms; in any host the URL names | same, `loopback`, `ip` | +| Host parameters | `host=` and `hostaddr=` are checked like the URL's hosts, then dialled as given | same, `url_hosts` | +| TLS | `sslmode=verify-full` and `verify-ca` are dialled as given: no host is rewritten, so the certificate's name still matches | `reach.rs` | +| A name resolving to loopback | Not resolved to be refused: a hosts entry that maps a name to 127.0.0.1 on the machine fails at its one dial (the create's reach check, `store.reach`, the create's daemon), and that failure carries the refusal's advice (`loopback_hint`, sent to the worker as `reach_hint`). The hint is added only on an `Apart` machine, only when the URL names at least one host by name (an address is read, never resolved, and every loopback one was refused), and only when no connection was made (`not_connected`: the client's `error connecting to server` or `timeout waiting for server`, a silent dial, the session's `no connection to the server was made`, or the daemon's `cannot reach PostgreSQL Store`), never when the server answered (a refused login, a missing database, any error it sent). One attempt: nothing redials | [`setup/calls.rs`](../../../../control/crates/layerfs-platform/src/setup/calls.rs) `loopback_hint`, [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) `not_connected`, [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `reach_check`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `from_machine`, [`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs) `unreached` | +| Names in the Sandbox | A `namespaces` Sandbox resolves names with its machine's resolver files, bound into its root at start ([Backends](../sandboxes/backends.md)); a remote host is reached through the machine's own NAT and DNS | [`helper mounts.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs) `resolver` | +| Per call | Only the operations that dial the Store's URL on their side build it in the caller (`Op::store_url`): `sandbox.create` (its daemon and reach check), Commit (its Branch's head and `expected`) and a Workspace status (its head). The worker process reads the Store per call, and the password travels only in that one request; building it is a record read and this check, no provider command. A close resolves it only to end the mount intents a forced unmount left, and runs without it when the machine cannot dial it, naming each intent it could not end in `left`. Every other operation (`sandbox.get`'s reads, mount, exec, cancel, unmount) asks only the Sandbox's daemon, which dials the URL its create gave it, and never reads the URL: a Sandbox can always be read and removed | [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `host_op`, `in_worker`; [`host/call.rs`](../../../../control/crates/layerfs-sandbox/src/host/call.rs) `store_url`; [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `close` | + +`url_hosts` keeps no userinfo and nothing here puts any part of the URL in a +message but a host ([`postgres_url.rs`](../../../../control/crates/layerfs-sandbox-backend/src/postgres_url.rs)). ## Forwards diff --git a/docs/architecture/control/sandboxes/backends.md b/docs/architecture/control/sandboxes/backends.md index 8d5db6c4aa..305d036f76 100644 --- a/docs/architecture/control/sandboxes/backends.md +++ b/docs/architecture/control/sandboxes/backends.md @@ -66,6 +66,15 @@ its commands use the network of the kernel that runs it: | `docker` on macOS (Docker Desktop) | Docker Desktop's VM | the worker container's own bridge network | | `lima`, `apple-container` | the VM's | the VM's | +A `namespaces` Sandbox also resolves names as the kernel that runs it does: +the init stage binds that machine's `/etc/resolv.conf` and `/etc/hosts` +read-only over the image's, so Docker Desktop's `host.docker.internal`, a +lima guest's `host.lima.internal`, a Linux Engine's `--add-host` entry and +any DNS name the machine resolves resolve in the Sandbox too. The image +copy leaves both files out: the binds are the Sandbox's only resolver +files. What a PostgreSQL Store's URL may name on each machine is +[Reach](../machines/workers-and-reach.md#reach-reachrs). + On a Linux host, then, a `namespaces` Sandbox on `native` or `docker` shares the host's kernel and network: its separation is its namespaces, cgroup, seccomp filter and command identity (uid 501), not a VM. No call option, @@ -242,7 +251,8 @@ environment overlay(lower = image, upper/work = the Sandbox's), /proc, /dev (fuse null zero full random urandom tty, pts, shm), /tmp, Sandbox directory and each Bind at their own paths, the - runtime layer read-only at /.layerfs/runtime; pivot + runtime layer read-only at /.layerfs/runtime, this host's + /etc/resolv.conf and /etc/hosts read-only over the root's; pivot v /.layerfs/runtime/lib/ld-linux- --inhibit-cache --library-path /.layerfs/runtime/lib layerfs-daemon --config @@ -258,6 +268,7 @@ environment | Image | `sha256:<64 hex>`, the archive's config digest; a `docker save` archive with uncompressed layers (gzip or zstd layers refused); unpacked once per digest under `/images` and shared read-only. A reopen unpacks nothing: an image gone is refused. | [`rootfs/mod.rs`](../../../../control/crates/layerfs-sandbox-backend/src/backend/namespaces/rootfs/mod.rs), [`types/image.rs`](../../../../control/crates/layerfs-sandbox-backend/src/types/image.rs), [`namespaces/provider.rs`](../../../../control/crates/layerfs-sandbox-backend/src/backend/namespaces/provider.rs) | | Helper | `LAYERFS_SANDBOX_HELPER`, else beside the daemon or this executable; copied into the Sandbox's `bin/`, which a reopen uses. | `namespaces/provider.rs` | | Runtime layer | `runtime/` beside the daemon (the sealed bundle's, R5), when it holds this architecture's loader; else none, and the daemon runs on the image's own loader and libraries as before. Copied into the Sandbox's `runtime/` (regular files of `lib/` and `bin/` only; anything else refused; the loader and programs 0755, the libraries 0644), so a bundle replaced under a running Sandbox changes nothing. The init stage binds it read-only, nosuid and nodev at `/.layerfs/runtime`, refusing an image whose `/.layerfs` or `/.layerfs/runtime` is not a plain directory, and starts the daemon through its loader (`--inhibit-cache --library-path /.layerfs/runtime/lib`) with `LAYERFS_SANDBOX_RUNTIME=/.layerfs/runtime` and no `LD_*` variable: the image's loader, libraries and `/etc/ld.so.cache` are never used, so an image with an older glibc, musl or no libc starts it. The image's `/etc/ld.so.preload` is still read by the loader. Its files are unmodified Debian binaries (glibc's loader and libraries, `libgcc_s`, OpenSSL, `getent`, `bash-static`, `busybox-static`), several GPL or LGPL: the bundle's `licenses/` holds each package's copyright file and `SOURCES`, the written source offer naming every file's Debian source package, version and snapshot.debian.org page (`sandbox_runtime.sources` in `bundle.json`); `tools/linux_bundle.py sources` downloads exactly those sources to publish beside a release. | `namespaces/provider.rs`, `namespaces/create.rs`, [`helper mounts.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs), [`helper init.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/init.rs), [`sandbox_runtime.rs`](../../../../engine/crates/layerfs-bridge/src/sandbox_runtime.rs) | +| Resolver files | `RESOLVER_FILES` (`/etc/resolv.conf`, `/etc/hosts`) of the launcher's root, each bound read-only at its own path in the Sandbox root, so the Sandbox, which shares the launcher's network namespace, resolves names as the launcher does. A mount point the image lacks is made empty, 0644, in the Sandbox's own writable layer, and one that is a link or another non-file is replaced there; an image whose `/etc` is not a plain directory (a bind through a link would leave the root before the pivot), or whose entry is a directory, keeps its own; a file the launcher lacks is not bound. They are never in a Workspace, a diff or a Commit: they land on the root's `/etc` (the image and the Sandbox's upper layer), Workspaces are mounted under the Sandbox directory, and `HelperSpec::resolver_targets` refuses the start when the Sandbox directory or a bind would hold one | [`helper_spec.rs`](../../../../control/crates/layerfs-sandbox-backend/src/helper_spec.rs), [`helper mounts.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs) `resolver` | | Commands | `helper exec --init --cgroup [--command-cgroup ] [--runtime ] --uid --gid --cwd -- `: forks itself into the Sandbox's leaf group `/init`, the only group a command helper uses (`clone3` with `CLONE_INTO_CGROUP`; the parent, outside it, waits and ends as its child did, a signal included), the child enters the namespaces, becomes uid:gid with no capabilities and no-new-privs, installs the filter below, execs. `--runtime /.layerfs/runtime` (a Sandbox with the runtime layer) appends `/.layerfs/runtime/bin` to the end of the command's `PATH` once; `argv[0]` (`bash`) is looked up on it inside the Sandbox, so the image's own `bash` wins and an image with none runs the runtime's static one. That directory holds only `bash`, `busybox` (no applet links) and `getent`. | [`namespaces/exec.rs`](../../../../control/crates/layerfs-sandbox-backend/src/backend/namespaces/exec.rs), [`helper exec.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/exec.rs) | | Command cgroup | With an exec slot, the command (never the helper) is created inside `ws-/exec-` (`clone3` with `CLONE_INTO_CGROUP`), without one inside the helper's (the leaf); once its exec succeeded the helper writes one byte on a socket it was given as stdin, and only then is the stop handle told. A command that cannot be created there never runs. No exec moves a process between groups: a write to `cgroup.procs` waits for an RCU grace period (5–28 ms after an idle spell), which every command paid before. Only the init stage joins its group, once per Sandbox. | `namespaces/exec.rs`, [`namespaces/cgroup.rs`](../../../../control/crates/layerfs-sandbox-backend/src/backend/namespaces/cgroup.rs) | | Sandbox group layout | The Sandbox's group `` holds no process: its init stages, daemon, command helpers and commands with no exec slot are in its leaf `/init`, commands with one in `ws-/exec-`. cgroup v2's no-internal-process rule allows only such a group to enable controllers for its children, so `create` splits it before any process joins and gives `init` and each `ws-` the memory and pids controllers it has: a Workspace's memory, processes and OOM kills can be read ([`sandbox.get`](../../api/sdk/sandbox.md#sandboxget) `workspaces[].usage`), and ``'s own files still count everything. `ws-` enables nothing for its command groups. No limit is ever written. | `namespaces/cgroup.rs` `create`, `split`, `leaf` | @@ -279,7 +290,9 @@ has `/dev/fuse` and a writable cgroup v2 tree, and the Sandbox root is the bundle's image archive. The bundle is bound into the container, so its `runtime/` is there beside the daemon. Its worker never sets `user.max_user_namespaces` (that would change the whole Docker host), so the command filter alone blocks -user namespaces. Docker publishes ports only when a container starts, so the +user namespaces. Its Sandboxes resolve names with the worker's resolver +files (above): `host.docker.internal` names this host on Docker Desktop. +Docker publishes ports only when a container starts, so the machine refuses a forward and every call goes through the worker ([Machines: platforms](../machines/platforms.md)). @@ -312,7 +325,7 @@ here times a command out | --- | --- | --- | | `types/` | `LaunchRequest`, `ProviderLaunchOptions`, `LocalRecord`, `NamespaceRecord`, `SandboxRecord`, `ExecRequest`, `ExecExit`, `SandboxInspection`, `CommandIdentity`, `Bind`, `Image`, `ContainerId` (a random 64-hex id per Sandbox), `RuntimeError` (`Io`, `Protocol`, `Unsupported`), `WireFailure` (whether attempted). They compile on Windows too. | [`types/`](../../../../control/crates/layerfs-sandbox-backend/src/types) | | `steps.rs` | Step times of a traced command (`exec.*`, and the helper's `helper.*` via `--trace `). | [`steps.rs`](../../../../control/crates/layerfs-sandbox-backend/src/steps.rs) | -| `postgres_url.rs` | Splits a PostgreSQL URL at its host so a daemon gets the same URL under another host name; no `Debug`, never in a message. | [`postgres_url.rs`](../../../../control/crates/layerfs-sandbox-backend/src/postgres_url.rs) | +| `postgres_url.rs` | Reads every server host a `postgres://` URL names, as its client (tokio-postgres) reads them (`url_hosts`: the host list and `host`/`hostaddr` parameters, percent-decoded), and says which name this host's loopback (`loopback`, with `ip` reading every IPv4 form `inet_aton` reads and IPv6 zone ids), so a machine that does not share it can refuse it; the URL is never rewritten and never in a message. | [`postgres_url.rs`](../../../../control/crates/layerfs-sandbox-backend/src/postgres_url.rs) | | `platform_policy.rs` | Platforms removed in 2.0 (`firecracker`, `microsandbox`, `ssh`): a record naming one is refused, never run. | [`platform_policy.rs`](../../../../control/crates/layerfs-sandbox-backend/src/platform_policy.rs) | | `json.rs` | A small streaming JSON reader (image manifests) and the quoting `SUPPORT.json` is written with. | [`json.rs`](../../../../control/crates/layerfs-sandbox-backend/src/json.rs) | diff --git a/docs/architecture/control/sandboxes/daemon-channel-and-exec.md b/docs/architecture/control/sandboxes/daemon-channel-and-exec.md index 99ccd4bbf9..4e3f176878 100644 --- a/docs/architecture/control/sandboxes/daemon-channel-and-exec.md +++ b/docs/architecture/control/sandboxes/daemon-channel-and-exec.md @@ -124,7 +124,8 @@ replays. A cancel at spawn may end the command under SIGTERM (143) or SIGKILL ```text caller: on_machine / reach(record, Call) resolve project -> Store kind; PostgreSQL URL resolved here (password - included, loopback host rewritten to the machine's alias), never written + included, never rewritten; a loopback host the machine does not share + refused, no machine asked), never written place::on_machine(machine) | | Executor::Local Executor::Worker diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 02116ee318..2de9f0efba 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -97,7 +97,7 @@ another operation holds the Store | Call | Does | Refusals | Source | | --- | --- | --- | --- | -| `store.connect` | records the database as a Store in the fixed `layerfs` schema: URL with no user or password, schema, `synchronous_commit`, its saved login `auth`, binding, a cursor key of this home's own, no machine. On a connected Store the URL becomes the address every machine dials (`readdress`); with `--machine ` it is that machine's own, `machines.: {url}`, checked from the side that dials (this process, or the worker's `store.reach`), and the machine's platform must run PostgreSQL Sandboxes. Both refuse `--auth` and `--synchronous-commit` | `InvalidInput`, `Exists`, `NotFound` (no such saved login), `Unavailable`, `Unsupported` (`--machine` on a platform that runs no PostgreSQL Sandbox), `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | +| `store.connect` | records the database as a Store in the fixed `layerfs` schema: URL with no user or password, schema, `synchronous_commit`, its saved login `auth`, binding, a cursor key of this home's own, no machine. On a connected Store the URL becomes the address every machine dials (`readdress`); with `--machine ` it is that machine's own, `machines.: {url}`, checked from the side that dials (this process, or the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself), and the machine's platform must run PostgreSQL Sandboxes. Both refuse `--auth` and `--synchronous-commit` | `InvalidInput`, `Exists`, `NotFound` (no such saved login), `Unavailable`, `Unsupported` (`--machine` on a platform that runs no PostgreSQL Sandbox), `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | | `store.disconnect` | forgets the Store; its data stays. With `--machine `, removes that machine's own address, which then dials the Store's, and forgets its reach | `InvalidInput` for sqlite (`store remove`); `InUse` while leased or a Sandbox uses it; `NotFound` when the machine has neither an address of its own nor a reach | same | | `store.update {auth, synchronous_commit}` | another saved login or `synchronous_commit` (one is required); a new login is checked once from this process on the Store's address, which must hold this Store, and saved again under the home lock; the write is clean (`StoreRecord::cleaned`) | `InvalidInput`; `Unavailable` (not reached, or another Store's schema); `Conflict` if the record changed meanwhile | [`update.rs`](../../../../control/crates/layerfs-store/src/postgresql/update.rs) | | Store calls | open the schema in this process with the URL resolved now | — | [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) | @@ -174,13 +174,13 @@ update as its fix | Put in again on each call; the full URL is never written to a record, log, trace or `Debug` output | same; [`host/frame.rs`](../../../../control/crates/layerfs-sandbox/src/host/frame.rs) `decode` | | The daemon runs `--config `; the setup is in neither its arguments nor its environment; `DaemonStore` prints `url` as `[redacted]` | [`local/create.rs`](../../../../control/crates/layerfs-sandbox-backend/src/local/create.rs), [`store.rs`](../../../../engine/crates/layerfs-bridge/src/store.rs) | -How the URL is rewritten for a machine is +The URL is never rewritten for a machine; which URLs a machine refuses is [Reach](../machines/workers-and-reach.md#reach-reachrs). ## Related - [Stores and projects](README.md): records, routes and leases. -- [Machines: workers and reach](../machines/workers-and-reach.md): `store.file`, `store.reach` and URL rewriting. +- [Machines: workers and reach](../machines/workers-and-reach.md): `store.file`, `store.reach` and the loopback refusal. - [Backups](../backups/README.md): `Stage` and `Unstage` for `backup.create`. - [Store: SQLite](../../engine/store/sqlite.md), [Store: PostgreSQL](../../engine/store/postgresql.md): what the engine opens. - [API: store](../../api/sdk/store.md). diff --git a/docs/architecture/engine/store/postgresql.md b/docs/architecture/engine/store/postgresql.md index 7dba0d8961..35808412a5 100644 --- a/docs/architecture/engine/store/postgresql.md +++ b/docs/architecture/engine/store/postgresql.md @@ -70,7 +70,7 @@ There is no `postgresql` cargo feature: every build serves both Store kinds. | `Light` check | A Sandbox daemon's writer, Workspace and control readers, and `attach_read_only`; a hand-changed column fails the statement that uses it instead | [`bootstrap.rs`](../../../../engine/crates/layerfs-store-service/src/bootstrap.rs), [`owner.rs`](../../../../engine/crates/layerfs-daemon/src/application/owner.rs) | | `binding(selection)` | The binding key a schema records, read in one read-only session, so a home that did not create it can open it | [`store/postgresql.rs`](../../../../engine/crates/layerfs-persistence/src/store/postgresql.rs) | | `attach_read_only(selection)` | One read-only session under the recorded binding, returned for the caller to compare with its own | same | -| `postgresql_access(url, schema)` | Server version, one round trip's latency, `current_user`, whether the schema exists, and each privilege the role lacks: the schema's `USAGE` and `CREATE`, the database's `CREATE` (compaction creates the scratch schema) and `TEMP` (merges stage in temporary tables; compaction reads its visited set from them), `pg_read_all_stats` (compaction reads the recorded owner's `pg_stat_activity` row and calls `pg_terminate_backend`), each table's `SELECT`/`INSERT`/`UPDATE`/`DELETE` and each sequence's `USAGE` | [`access.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/access.rs) | +| `postgresql_access(url, schema)` | Server version, one round trip's latency, `current_user`, whether the schema exists, and each privilege a Sandbox's reads and writes need that the role lacks: the schema's `USAGE` and `CREATE`, the database's `TEMP` (merges stage in temporary tables), each table's `SELECT`/`INSERT`/`UPDATE`/`DELETE` and each sequence's `USAGE`. What only a compaction needs (the database's `CREATE`, `pg_read_all_stats`) is not asked: `compaction_missing` checks it when a compaction starts | [`access.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/access.rs) | | `postgresql_status(url, schemas)` | Server version, one round trip's latency and each named schema's size | [`status.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/status.rs) | `access` and `status` open one connection for the call and close it, run @@ -87,9 +87,13 @@ deadline. `Connector::new` pairs a single `localhost` host (with no 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 -compaction session in one read-only round trip, before the intent, the mark -and the `lfs_gc_` scratch schema; the first privilege the role lacks is +`compaction_missing(session)` checks what a compaction needs Store-wide on +the compaction session in one read-only round trip: the schema's `USAGE` and +`CREATE`, the database's `CREATE` (the scratch schema) and `TEMP` (its +visited set), `pg_read_all_stats` (the recorded owner's `pg_stat_activity` +row and its `pg_terminate_backend`) and ownership of the Store's tables, +before the intent, the mark and the `lfs_gc_` scratch schema; the first +privilege the role lacks is `Unsupported`, naming it (AC-44). It is reachable from a session because a compaction holds one already and never retains the URL. `PostgresSelection`'s `Debug` redacts the URL. diff --git a/docs/versioned/2.0.0/calls.md b/docs/versioned/2.0.0/calls.md index 8941ecc0a7..5c91474201 100644 --- a/docs/versioned/2.0.0/calls.md +++ b/docs/versioned/2.0.0/calls.md @@ -1510,6 +1510,17 @@ $ layerfs store disconnect shop-pg --detail {"ok":true,"outcome":"disconnected","store":"shop-pg","machine":null} ``` +The URL above names `127.0.0.1`, which works only where the Sandbox's +machine shares this computer's loopback: `native` and `docker` on a Linux +Engine. On `docker` with Docker Desktop, `lima` or `apple-container` a +`sandbox create --machine` refuses it `Unsupported`, naming what that +machine calls this computer; give the Store a host the machine reaches, or +that machine its own URL with `layerfs store connect shop-pg '' +--machine `. That check, like the first connect, needs no +privilege beyond what a Sandbox's reads and writes need: what only +`store compact` needs (`pg_read_all_stats`, `CREATE` on the database) is +checked when a compaction starts. + See [Stores](machines-and-stores.md#stores). ### `backup` (6) diff --git a/docs/versioned/2.0.0/machines-and-stores.md b/docs/versioned/2.0.0/machines-and-stores.md index 7a8c7cd2d4..b9127144c1 100644 --- a/docs/versioned/2.0.0/machines-and-stores.md +++ b/docs/versioned/2.0.0/machines-and-stores.md @@ -472,12 +472,20 @@ shown in [the calls](calls.md#store-13).) another machine whose platform runs PostgreSQL Sandboxes (`native` on macOS and Linux, `docker`, `lima`, `apple-container`); `sandbox create` checks from the machine that the server answers and holds this Store. - The caller rewrites a loopback host for the machine (`docker`: - `host.docker.internal`; `lima`: `192.168.5.2`; `apple-container`: the - container network's gateway, read from `container inspect`, which needs - the server listening on that bridge); the login travels only in that one - request. The server always runs off the machine; nothing installs - PostgreSQL in a machine (D12). + The URL is dialled exactly as configured, never rewritten. On a machine + that does not share this computer's loopback (`docker` on Docker + Desktop, `lima`, `apple-container`) a URL naming it (`localhost`, + 127.0.0.0/8, `0.0.0.0`, `::1`, in any spelling) or a Unix socket is + refused `Unsupported`, naming what the machine calls this computer + (`host.docker.internal`; `host.lima.internal`; `apple-container`: its + network's gateway, on which the server must listen) and the per-machine + URL call `layerfs store connect --machine `; + `native` and `docker` on a Linux Engine share the loopback and dial it + as given. A Sandbox resolves names as its machine does. Only the calls + that dial the URL (`sandbox create`, Commit, a Workspace status) are + refused for it: a Sandbox can always be read and removed. The login + travels only in the one request. The server always runs off the + machine; nothing installs PostgreSQL in a machine (D12). - `store doctor ` checks the Store from this computer and from each machine that has an address of its own or a Sandbox of it (`--machine M` adds one), each as one `store.connection` row with `from`, and records diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs index d12f7e5288..bda47617e1 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs @@ -1,8 +1,10 @@ //! What a role may do in a Store's schema, for the check of a //! machine's connection and for a PostgreSQL compaction's preflight: the //! server's version, one round trip's latency, the role, and each privilege -//! the Store's writes and compaction need that it lacks. One connection -//! opened for the call and closed after it, read-only queries only, no retry. +//! it lacks that a Sandbox's reads and writes need ([`access`]) or that a +//! compaction needs ([`compaction_missing`], which a compaction checks for +//! itself). One connection opened for the call and closed after it, +//! read-only queries only, no retry. use crate::backend::postgresql::session::connection::{Connector, Session}; use crate::backend::postgresql::status::PostgresStatusError; use crate::backend::records::{BackendError, Param}; @@ -21,27 +23,24 @@ pub struct PostgresAccess { pub role: String, /// Whether the database has the schema. pub schema: bool, - /// Each privilege the role lacks, as ` on `, in a - /// fixed order: the schema's `USAGE` and `CREATE`, the database's - /// `CREATE` and `TEMP`, `pg_read_all_stats`, then each table's `SELECT`, - /// `INSERT`, `UPDATE`, `DELETE` and each sequence's `USAGE`. Empty when - /// the role has them all (or there is no schema). + /// Each privilege a Sandbox's reads and writes need that the role + /// lacks, as ` on `, in a fixed order: the schema's + /// `USAGE` and `CREATE`, the database's `TEMP`, then each table's + /// `SELECT`, `INSERT`, `UPDATE`, `DELETE` and each sequence's `USAGE`. + /// Empty when the role has them all (or there is no schema). What only + /// a compaction needs (`CREATE` on the database, `pg_read_all_stats`) + /// is not asked here: a compaction checks it before it starts. pub missing: Vec, } -/// The role, the schema's `USAGE` and `CREATE` (NULL without the schema), the -/// database's `CREATE` (a compaction creates the `lfs_gc_` scratch -/// schema) and `TEMP` (a merge stages in temporary tables, and a compaction -/// reads its visited set from them), and `pg_read_all_stats` (a compaction -/// reads another backend's `pg_stat_activity` row). +/// The role, the schema's `USAGE` and `CREATE` (NULL without the schema) and +/// the database's `TEMP` (a merge stages in temporary tables). const ROLE: &str = "SELECT current_user::text, \ CASE WHEN EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1::text) \ THEN has_schema_privilege($1::text, 'USAGE') END, \ CASE WHEN EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1::text) \ THEN has_schema_privilege($1::text, 'CREATE') END, \ - has_database_privilege(current_database(), 'CREATE'), \ - has_database_privilege(current_database(), 'TEMP'), \ - pg_has_role('pg_read_all_stats', 'MEMBER')"; + has_database_privilege(current_database(), 'TEMP')"; /// Each table and sequence privilege of the schema the role lacks. const MISSING: &str = "SELECT p.privilege || ' on ' || $1::text || '.' || c.relname \ @@ -129,9 +128,7 @@ pub fn access(url: &str, schema: &str) -> Result = row.try_get(1).map_err(failed)?; let create_schema: Option = row.try_get(2).map_err(failed)?; - let create_database: bool = row.try_get(3).map_err(failed)?; - let temp: bool = row.try_get(4).map_err(failed)?; - let read_all_stats: bool = row.try_get(5).map_err(failed)?; + let temp: bool = row.try_get(3).map_err(failed)?; let mut missing = Vec::new(); if usage == Some(false) { missing.push(format!("USAGE on schema {schema}")); @@ -139,15 +136,9 @@ pub fn access(url: &str, schema: &str) -> Result::new(), "{access:?}"); + assert_eq!(access.role, role.name); +} + #[test] fn a_fully_privileged_role_compacts() { let Some(url) = url() else { return };