Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions crates/openshell-gateway/src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,35 @@ fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
}
}

/// The driver binary is not installed in any searched location.
///
/// Distinct from an invalid driver table so callers can treat an uninstalled
/// auto-detect candidate as absent while still failing on a genuine mistake.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinaryNotFound {
message: String,
}

impl std::fmt::Display for BinaryNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}

impl std::error::Error for BinaryNotFound {}

impl From<BinaryNotFound> for Error {
fn from(error: BinaryNotFound) -> Self {
Self::config(error.message)
}
}

/// Search `dirs` for `bin_name`, then next to the gateway executable.
pub fn resolve_binary(bin_name: &str, dirs: &[PathBuf], hint: &str) -> Result<PathBuf> {
pub fn resolve_binary(
bin_name: &str,
dirs: &[PathBuf],
hint: &str,
) -> std::result::Result<PathBuf, BinaryNotFound> {
let mut searched = Vec::new();
let sibling = std::env::current_exe()
.ok()
Expand All @@ -125,9 +152,11 @@ pub fn resolve_binary(bin_name: &str, dirs: &[PathBuf], hint: &str) -> Result<Pa
.map(|path| format!("'{}'", path.display()))
.collect::<Vec<_>>()
.join(", ");
Err(Error::config(format!(
"compute driver binary {bin_name} not found (searched {searched}); {hint}"
)))
Err(BinaryNotFound {
message: format!(
"compute driver binary {bin_name} not found (searched {searched}); {hint}"
),
})
}

/// A launch's private directory.
Expand Down
18 changes: 18 additions & 0 deletions crates/openshell-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,12 @@ impl openshell_server::ComputeDriverFactory for DockerFactory {
docker::DOCKER.validate(&docker_launch_plan(context)?)
}

fn is_installed(&self, context: openshell_server::ComputeDriverConfigContext<'_>) -> bool {
// A table that does not parse is not "uninstalled": report installed
// so validation surfaces the error.
docker_launch_plan(context).map_or(true, |plan| docker::DOCKER.is_installed(&plan))
}

async fn build(
&self,
context: openshell_server::ComputeDriverBuildContext<'_>,
Expand Down Expand Up @@ -451,6 +457,12 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory {
podman::PODMAN.validate(&podman_launch_plan(context)?)
}

fn is_installed(&self, context: openshell_server::ComputeDriverConfigContext<'_>) -> bool {
// A table that does not parse is not "uninstalled": report installed
// so validation surfaces the error.
podman_launch_plan(context).map_or(true, |plan| podman::PODMAN.is_installed(&plan))
}

async fn build(
&self,
context: openshell_server::ComputeDriverBuildContext<'_>,
Expand Down Expand Up @@ -524,6 +536,12 @@ impl openshell_server::ComputeDriverFactory for VmFactory {
vm::validate(&vm_launch_plan(context)?)
}

fn is_installed(&self, context: openshell_server::ComputeDriverConfigContext<'_>) -> bool {
// A table that does not parse is not "uninstalled": report installed
// so validation surfaces the error.
vm_launch_plan(context).map_or(true, |plan| vm::is_installed(&plan))
}

async fn build(
&self,
context: openshell_server::ComputeDriverBuildContext<'_>,
Expand Down
8 changes: 7 additions & 1 deletion crates/openshell-gateway/src/local_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl LocalDriver {
Ok(LaunchPlan { driver_dir, table })
}

fn binary(self, plan: &LaunchPlan) -> Result<PathBuf> {
fn binary(self, plan: &LaunchPlan) -> std::result::Result<PathBuf, launcher::BinaryNotFound> {
let binary = self.binary_name();
launcher::resolve_binary(
&binary,
Expand All @@ -89,6 +89,12 @@ impl LocalDriver {
)
}

/// Whether the driver binary can be found for this plan.
#[must_use]
pub fn is_installed(self, plan: &LaunchPlan) -> bool {
self.binary(plan).is_ok()
}

/// Validate the table with the driver's own `preflight`, which contacts no
/// backend and creates no state.
pub fn validate(self, plan: &LaunchPlan) -> Result<()> {
Expand Down
10 changes: 9 additions & 1 deletion crates/openshell-gateway/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,22 @@ impl VmLaunchPlan {
/// Resolution order: `driver_dir` from `[openshell.drivers.vm]`, or when it
/// is unset the conventional install directories, then the directory of the
/// gateway's own executable so development builds work out of the box.
pub fn resolve_compute_driver_bin(driver_dir: Option<&Path>) -> Result<PathBuf> {
pub fn resolve_compute_driver_bin(
driver_dir: Option<&Path>,
) -> std::result::Result<PathBuf, launcher::BinaryNotFound> {
launcher::resolve_binary(
DRIVER_BIN_NAME,
&launcher::driver_search_dirs(driver_dir),
DRIVER_BIN_HINT,
)
}

/// Whether the `openshell-driver-vm` binary can be found for this plan.
#[must_use]
pub fn is_installed(plan: &VmLaunchPlan) -> bool {
resolve_compute_driver_bin(plan.driver_dir.as_deref()).is_ok()
}

/// Validate the table with the driver's own `preflight`, which contacts no
/// backend and creates no state.
pub fn validate(plan: &VmLaunchPlan) -> Result<()> {
Expand Down
67 changes: 67 additions & 0 deletions crates/openshell-gateway/tests/config_preflight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,3 +299,70 @@ async fn unrelated_driver_does_not_require_vm_tools() {
assert!(output.status.success(), "{}", combined(&output));
assert!(!combined(&output).contains("VM host tool"));
}

impl Fixture {
/// A shared config with Docker and Podman tables and no VM table.
fn write_docker_podman_config(&self, driver: Option<&str>) {
let selector =
driver.map_or_else(String::new, |name| format!("compute_driver = {name:?}\n"));
let driver_dir = toml::Value::try_from(&self.tools).expect("serialize driver directory");
fs::write(&self.config, format!(
"[openshell]\nversion = 2\n[openshell.gateway]\ndisable_tls = true\ndriver_dir = {driver_dir}\n{selector}[openshell.drivers.docker]\n[openshell.drivers.podman]\n"
)).expect("gateway configuration");
}

fn driver_script(&self, name: &str, accept_table: bool) {
let verdict = if accept_table {
"test \"$1\" = preflight"
} else {
"echo 'unknown field' >&2\nexit 3"
};
self.tool(
&format!("openshell-driver-{name}"),
&format!("while read -r _; do :; done\n{verdict}"),
);
}
}

#[tokio::test]
async fn uninstalled_auto_detect_driver_is_skipped_without_selection() {
let fixture = Fixture::new();
fixture.write_docker_podman_config(None);
fixture.driver_script("docker", true);
let output = fixture.run(&[]).await;
assert!(output.status.success(), "{}", combined(&output));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("skipping the podman compute driver"),
"{stderr}"
);
}

#[tokio::test]
async fn explicitly_selected_uninstalled_driver_fails() {
let fixture = Fixture::new();
fixture.write_docker_podman_config(Some("podman"));
fixture.driver_script("docker", true);
let output = fixture.run(&[]).await;
assert!(!output.status.success(), "{}", combined(&output));
assert!(
normalized_diagnostic(&output).contains("openshell-driver-podman not found"),
"{}",
combined(&output)
);
}

#[tokio::test]
async fn installed_auto_detect_driver_with_invalid_table_still_fails() {
let fixture = Fixture::new();
fixture.write_docker_podman_config(None);
fixture.driver_script("docker", true);
fixture.driver_script("podman", false);
let output = fixture.run(&[]).await;
assert!(!output.status.success(), "{}", combined(&output));
assert!(
normalized_diagnostic(&output).contains("invalid [openshell.drivers.podman] table"),
"{}",
combined(&output)
);
}
16 changes: 16 additions & 0 deletions crates/openshell-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,22 @@ fn run_effective_config_preflight(
..driver_startup
};
validate_preflight_isolation_backend(&candidate_file, driver_name)?;
// Runtime detection skips a driver that is not installed, so
// a shared config naming one must not fail preflight. A
// present binary with an invalid table still fails below.
if !crate::auto_detect_candidate_installed(
compute_drivers,
driver_name,
run.name.trim(),
SocketAddr::new(run.bind_address, run.port),
&run.log_level,
candidate_startup,
) {
eprintln!(
"note: skipping the {driver_name} compute driver in preflight: its driver binary is not installed"
);
continue;
}
crate::validate_compute_driver_config(
compute_drivers,
driver_name,
Expand Down
38 changes: 38 additions & 0 deletions crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1840,6 +1840,17 @@ pub trait ComputeDriverFactory: Send + Sync {
Ok(())
}

/// Whether this driver's executable is installed on this host.
///
/// Config preflight with no explicit `compute_driver` asks this of each
/// auto-detect candidate that has a driver table, and skips an
/// uninstalled one the way runtime detection does. An explicitly selected
/// driver is always validated. Must not start processes or open sockets.
/// A driver that cannot tell keeps the default and is always validated.
fn is_installed(&self, _context: ComputeDriverConfigContext<'_>) -> bool {
true
}

/// Whether [`Self::validate_config`] fully validates this factory's
/// configuration without runtime side effects.
fn supports_config_preflight(&self) -> bool {
Expand Down Expand Up @@ -2777,6 +2788,33 @@ fn validate_compute_driver_config(
Ok(driver)
}

/// Whether an auto-detect candidate's driver is installed. Candidates that do
/// not resolve to a registered factory count as installed so that validation
/// reports the real problem.
fn auto_detect_candidate_installed(
registry: &ComputeDriverRegistry,
driver_name: &str,
gateway_name: &str,
gateway_bind_address: SocketAddr,
gateway_log_level: &str,
driver_startup: compute::driver_config::DriverStartupContext<'_>,
) -> bool {
match resolve_configured_compute_driver(registry, driver_name, driver_startup) {
Ok(ConfiguredComputeDriver::Registered(registration)) => {
registration
.factory
.is_installed(ComputeDriverConfigContext {
driver_name: &registration.name,
gateway_name,
gateway_bind_address,
gateway_log_level,
driver_startup,
})
}
_ => true,
}
}

const SUPERVISOR_POOL_WITHOUT_HOST: &str = "openshell.gateway.supervisor_pool tunes the shared \
supervisor pool, but no compute driver hosts sandboxes on it; set the Kubernetes driver's \
supervisor_topology = \"gateway\" or remove the table";
Expand Down
2 changes: 1 addition & 1 deletion docs/how-it-works/gateways/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2294,7 +2294,7 @@ changing it:
openshell-gateway config preflight --path ~/.config/openshell/gateway.toml
```

Without `--path`, the command validates a nonempty `OPENSHELL_GATEWAY_CONFIG`. Otherwise, it validates an existing XDG gateway config when one is discovered. When neither source selects a config, preflight validates the effective daemon arguments. An explicit missing path, a legacy schema-v1 file, invalid TOML, a symlink, or any nonregular file fails. Preflight merges the selected file with the current `OPENSHELL_*` environment and applies the daemon's read-only startup checks. These checks include selector and socket normalization, registered-driver selection and configuration, rate-limit pairs, TLS and mTLS relationships, interceptor registrations, and supervisor middleware registrations. When a selected file omits `compute_driver`, preflight validates each configured table for an auto-detectable driver without running the runtime detection probes, which can connect local sockets or launch discovery commands. It validates configured driver TLS requirements, including the gateway CA, without requiring package-generated certificate files to exist before certificate generation. It does not construct a compute driver or connect to a transport. A failed preflight always preserves the file; it never migrates, replaces, or rewrites configuration.
Without `--path`, the command validates a nonempty `OPENSHELL_GATEWAY_CONFIG`. Otherwise, it validates an existing XDG gateway config when one is discovered. When neither source selects a config, preflight validates the effective daemon arguments. An explicit missing path, a legacy schema-v1 file, invalid TOML, a symlink, or any nonregular file fails. Preflight merges the selected file with the current `OPENSHELL_*` environment and applies the daemon's read-only startup checks. These checks include selector and socket normalization, registered-driver selection and configuration, rate-limit pairs, TLS and mTLS relationships, interceptor registrations, and supervisor middleware registrations. When a selected file omits `compute_driver`, preflight validates each configured table for an auto-detectable driver without running the runtime detection probes, which can connect local sockets or launch discovery commands. It skips a configured table whose driver binary is not installed, with a note on stderr, as runtime detection does, but it still fails when the binary is present and the table is invalid. Selecting that driver with `compute_driver` fails when its binary is missing. It validates configured driver TLS requirements, including the gateway CA, without requiring package-generated certificate files to exist before certificate generation. It does not construct a compute driver or connect to a transport. A failed preflight always preserves the file; it never migrates, replaces, or rewrites configuration.

Config preflight validates configuration without loading launch-signing keys, so a successful result does not confirm that the key files exist or form a usable pair. Gateway startup validates configured or discovered signing bundles. Sandbox creation checks the selected driver's launch-signing requirement before image preparation.

Expand Down
Loading