Skip to content

Commit f882dcb

Browse files
committed
Merge branch 'codex/vm-host-supervisor' into codex/docker-host-supervisor
# Conflicts: # crates/openshell-sandbox/src/lib.rs # crates/openshell-sandbox/src/main.rs
2 parents e3b8a72 + 0c5cd41 commit f882dcb

7 files changed

Lines changed: 215 additions & 51 deletions

File tree

‎crates/openshell-core/src/sandbox_env.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,13 @@ pub const TELEMETRY_ENABLED: &str = "OPENSHELL_TELEMETRY_ENABLED";
122122
/// `"sidecar"`; the default combined supervisor path omits it.
123123
pub const SUPERVISOR_TOPOLOGY: &str = "OPENSHELL_SUPERVISOR_TOPOLOGY";
124124

125+
/// The isolation backend admitted by the deployment configuration (RFC 0012).
126+
///
127+
/// Delivered on a channel separate from the topology descriptor so descriptor
128+
/// verification against the admitted backend is not self-referential. Required
129+
/// whenever a topology descriptor is supplied.
130+
pub const ADMITTED_ISOLATION_BACKEND: &str = "OPENSHELL_ADMITTED_ISOLATION_BACKEND";
131+
125132
/// Network enforcement backend selected by the compute driver.
126133
pub const NETWORK_ENFORCEMENT_MODE: &str = "OPENSHELL_NETWORK_ENFORCEMENT_MODE";
127134

‎crates/openshell-driver-vm/src/driver.rs‎

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ use crate::rootfs::{
1919
sandbox_guest_runtime_identity, set_rootfs_image_file_mode, write_rootfs_image_file,
2020
};
2121
use crate::runtime::VmBackend;
22-
use base64::Engine as _;
2322
use bollard::Docker;
2423
use bollard::errors::Error as BollardError;
2524
use bollard::models::ContainerCreateBody;
@@ -171,6 +170,11 @@ const GUEST_SANDBOX_TOKEN_PATH: &str = openshell_core::container_paths::VM_GUEST
171170
const GUEST_INIT_DROPIN_DIR: &str = openshell_core::container_paths::VM_GUEST_INIT_DROPIN_DIR;
172171
const GUEST_BOUNDARY_CONFIG_PATH: &str = "/etc/openshell/vm-guest.json";
173172
const HOST_SANDBOX_TOKEN_FILE: &str = "sandbox.jwt";
173+
const HOST_TOPOLOGY_PAYLOAD_FILE: &str = "topology.payload";
174+
/// The backend this driver's deployment admits, delivered to the supervisor on
175+
/// a channel separate from the topology descriptor so descriptor verification
176+
/// is not self-referential.
177+
const DRIVER_ADMITTED_BACKEND: &str = "vm";
174178
#[cfg(target_os = "linux")]
175179
const HOST_SUPERVISOR_BINARY: &str = "host-runtime/openshell-sandbox";
176180
const VM_CONTROL_SOCKET: &str = "control.sock";
@@ -613,6 +617,23 @@ impl VmDriver {
613617
let payload = topology
614618
.encode()
615619
.map_err(|error| Status::internal(error.to_string()))?;
620+
// The payload carries the boundary bootstrap token, so it must not
621+
// appear in the world-readable process cmdline; deliver it through a
622+
// driver-owned 0600 file like the gateway token.
623+
let payload_path = state_dir.join(HOST_TOPOLOGY_PAYLOAD_FILE);
624+
tokio::fs::write(&payload_path, &payload)
625+
.await
626+
.map_err(|error| Status::internal(format!("write host topology payload: {error}")))?;
627+
#[cfg(unix)]
628+
tokio::fs::set_permissions(&payload_path, fs::Permissions::from_mode(0o600))
629+
.await
630+
.map_err(|error| {
631+
Status::internal(format!("restrict host topology payload: {error}"))
632+
})?;
633+
let main_process_spec = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec(
634+
sandbox.spec.as_ref(),
635+
)
636+
.map_err(|error| Status::internal(format!("encode main process spec: {error}")))?;
616637
let sandbox_user_id = self.config.resolve_sandbox_uid();
617638
let primary_group_id = self.config.resolve_sandbox_gid(sandbox_user_id);
618639
let mut command = Command::new(&supervisor_binary);
@@ -630,14 +651,18 @@ impl VmDriver {
630651
))
631652
.arg("--topology-backend-name=vm")
632653
.arg(format!("--topology-version={INTERFACE_VERSION}"))
633-
.arg(format!(
634-
"--topology-payload-base64={}",
635-
base64::engine::general_purpose::STANDARD.encode(payload)
636-
))
654+
.arg("--topology-payload-file")
655+
.arg(&payload_path)
637656
.arg("--workdir")
638657
.arg("/sandbox")
639-
.arg("--")
640-
.args(["/bin/sh", "-lc", "while :; do sleep 3600; done"])
658+
.env(
659+
openshell_core::sandbox_env::ADMITTED_ISOLATION_BACKEND,
660+
DRIVER_ADMITTED_BACKEND,
661+
)
662+
.env(
663+
openshell_core::sandbox_env::MAIN_PROCESS_SPEC,
664+
main_process_spec,
665+
)
641666
.env(
642667
openshell_core::sandbox_env::ENDPOINT,
643668
&self.config.openshell_endpoint,

‎crates/openshell-driver-vm/src/isolation/backend.rs‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ use super::protocol::{
3535
};
3636

3737
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
38+
/// How long one control call keeps retrying guest connect attempts. Boot-time
39+
/// callers retry whole calls above this; past boot, exhausting this window
40+
/// means the VM (or its launcher) is gone rather than still starting.
41+
const CONNECT_RETRY_TIMEOUT: Duration = Duration::from_secs(30);
3842
const MIN_BOOTSTRAP_TOKEN_BYTES: usize = 32;
3943

4044
/// Hypervisor-specific host-to-guest control transport.
@@ -313,7 +317,16 @@ impl BoundaryProcess for VmProcess {
313317
.call_wait(Request::Wait {
314318
process_id: self.process_id.clone(),
315319
})
316-
.await?;
320+
.await
321+
.map_err(|error| match error {
322+
// A wait that can no longer reach the guest leaf means the
323+
// boundary is gone, not that a retry could still observe the
324+
// exit status; report boundary loss per the contract.
325+
BackendError::Unavailable(message) => {
326+
BackendError::Terminated(format!("guest boundary lost during wait: {message}"))
327+
}
328+
error => error,
329+
})?;
317330
let Response::Exited { status } = response else {
318331
return Err(unexpected_response("exited", &response));
319332
};
@@ -709,9 +722,11 @@ impl GuestClient {
709722
}
710723

711724
async fn connect_vsock(&self) -> Result<BoundaryDuplexStream, BackendError> {
725+
let deadline = tokio::time::Instant::now() + CONNECT_RETRY_TIMEOUT;
712726
loop {
713727
match self.connect_vsock_once().await {
714728
Ok(stream) => return Ok(stream),
729+
Err(error) if tokio::time::Instant::now() >= deadline => return Err(error),
715730
Err(_) => tokio::time::sleep(Duration::from_millis(25)).await,
716731
}
717732
}

‎crates/openshell-driver-vm/src/isolation/guest.rs‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,10 @@ mod linux {
308308
config: GuestConfig,
309309
process_runtime: tokio::runtime::Handle,
310310
state: Mutex<RuntimeState>,
311+
/// The wire policy bound at first attach, so an idempotent attach retry
312+
/// carrying a different policy is denied instead of silently keeping
313+
/// the first policy.
314+
attached_policy: Mutex<Option<SandboxPolicyWire>>,
311315
next_exec_id: AtomicU64,
312316
exec_handles: Mutex<std::collections::HashMap<String, ExecHandle>>,
313317
}
@@ -425,6 +429,7 @@ mod linux {
425429
config,
426430
process_runtime,
427431
state: Mutex::new(RuntimeState::AwaitingAttach),
432+
attached_policy: Mutex::new(None),
428433
next_exec_id: AtomicU64::new(1),
429434
exec_handles: Mutex::new(std::collections::HashMap::new()),
430435
}
@@ -435,7 +440,7 @@ mod linux {
435440
return guest_error("denied", "control authentication failed");
436441
}
437442
match envelope.request {
438-
Request::Attach { policy } => self.attach((*policy).into()),
443+
Request::Attach { policy } => self.attach(*policy),
439444
Request::Confirm => self.confirm(),
440445
Request::StartAgent {
441446
sandbox_id,
@@ -572,27 +577,40 @@ mod linux {
572577
session: ExecSession,
573578
) -> Result<(), String> {
574579
let process_id = process_id.to_string();
575-
self.process_runtime.block_on(async move {
580+
let bridged = self.process_runtime.block_on(async move {
576581
let stream = stream.into_tokio()?;
577582
bridge_exec_stream(stream, session).await
578-
})?;
583+
});
584+
// Remove the handle even when the bridge fails; a failed stream
585+
// must not leak its exec registration.
579586
lock(&self.exec_handles).remove(&process_id);
580-
Ok(())
587+
bridged
581588
}
582589

583-
fn attach(&self, policy: openshell_core::policy::SandboxPolicy) -> Response {
590+
fn attach(&self, policy: SandboxPolicyWire) -> Response {
584591
let mut state = lock(&self.state);
585592
match &*state {
586593
RuntimeState::AwaitingAttach => {
587-
let prepared = match PreparedBoundary::establish(&self.process_runtime, &policy)
588-
{
594+
let prepared = match PreparedBoundary::establish(
595+
&self.process_runtime,
596+
&policy.clone().into(),
597+
) {
589598
Ok(prepared) => prepared,
590599
Err(error) => return guest_error("failed", error),
591600
};
601+
*lock(&self.attached_policy) = Some(policy);
592602
*state = RuntimeState::Bound(prepared);
593603
Response::Attached
594604
}
595-
RuntimeState::Bound(_) => Response::Attached,
605+
RuntimeState::Bound(_) => {
606+
// Idempotent retry of the same attach; a different policy
607+
// must not be silently coalesced onto the bound boundary.
608+
if lock(&self.attached_policy).as_ref() == Some(&policy) {
609+
Response::Attached
610+
} else {
611+
guest_error("denied", "attach policy does not match the bound boundary")
612+
}
613+
}
596614
_ => guest_error("invalid", "boundary has already advanced past attach"),
597615
}
598616
}

‎crates/openshell-driver-vm/src/isolation/protocol.rs‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -347,16 +347,37 @@ pub struct SandboxPolicyWire {
347347

348348
impl From<SandboxPolicy> for SandboxPolicyWire {
349349
fn from(policy: SandboxPolicy) -> Self {
350+
// Exhaustively destructure the policy so adding a `SandboxPolicy`
351+
// field is a compile error here instead of a silently dropped field
352+
// across the host-to-guest trust boundary.
353+
let SandboxPolicy {
354+
version,
355+
filesystem,
356+
network,
357+
landlock,
358+
process,
359+
} = policy;
360+
let FilesystemPolicy {
361+
read_only,
362+
read_write,
363+
include_workdir,
364+
} = filesystem;
365+
let NetworkPolicy { mode, proxy } = network;
366+
let LandlockPolicy { compatibility } = landlock;
367+
let ProcessPolicy {
368+
run_as_user,
369+
run_as_group,
370+
} = process;
350371
Self {
351-
version: policy.version,
352-
read_only: policy.filesystem.read_only,
353-
read_write: policy.filesystem.read_write,
354-
include_workdir: policy.filesystem.include_workdir,
355-
network: NetworkModeWire::from(policy.network.mode),
356-
proxy_addr: policy.network.proxy.and_then(|proxy| proxy.http_addr),
357-
landlock: LandlockCompatibilityWire::from(policy.landlock.compatibility),
358-
run_as_user: policy.process.run_as_user,
359-
run_as_group: policy.process.run_as_group,
372+
version,
373+
read_only,
374+
read_write,
375+
include_workdir,
376+
network: NetworkModeWire::from(mode),
377+
proxy_addr: proxy.and_then(|proxy| proxy.http_addr),
378+
landlock: LandlockCompatibilityWire::from(compatibility),
379+
run_as_user,
380+
run_as_group,
360381
}
361382
}
362383
}

‎crates/openshell-sandbox/src/lib.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ pub async fn run_sandbox(
115115
process_enabled: bool,
116116
upstream_proxy_args: openshell_supervisor_network::upstream_proxy::UpstreamProxyArgs,
117117
topology_descriptor: Option<openshell_isolation_interface::contract::TopologyDescriptor>,
118+
admitted_isolation_backend: Option<String>,
118119
) -> Result<i32> {
119120
let (program, args) = command
120121
.split_first()
@@ -395,10 +396,14 @@ pub async fn run_sandbox(
395396
"isolation backends require combined network,process mode"
396397
));
397398
}
399+
// The admitted backend comes from the driver's deployment channel, not
400+
// from the descriptor under verification, so the registry's
401+
// admission-mismatch check has independent input.
402+
let admitted_backend_name = admitted_isolation_backend.ok_or_else(|| {
403+
miette::miette!("topology descriptor supplied without an admitted isolation backend")
404+
})?;
398405

399406
let ca_file_paths = Arc::new(std::sync::Mutex::new(None));
400-
let proxy_bind_ip = Arc::new(std::sync::Mutex::new(None));
401-
let admitted_backend_name = descriptor.backend_name.clone();
402407
let backend: Arc<dyn openshell_isolation_interface::contract::IsolationBackend> =
403408
match admitted_backend_name.as_str() {
404409
"vm" => Arc::new(openshell_driver_vm::VmHostBackend::new(
@@ -445,7 +450,9 @@ pub async fn run_sandbox(
445450
let network_mediation_source = bound.network_mediation_source();
446451
let host_gateway_ip = bound.host_gateway_ip();
447452
let dns_mediation_source = bound.dns_mediation_source();
448-
let mediation_bind_ip = *proxy_bind_ip.lock().expect("proxy bind IP lock");
453+
// Source-backed mediation consumes backend connections; there is no
454+
// listener to bind, so no override address applies.
455+
let mediation_bind_ip: Option<std::net::IpAddr> = None;
449456
let networking = openshell_supervisor_network::run::run_networking(
450457
&policy,
451458
mediation_bind_ip,

0 commit comments

Comments
 (0)