Skip to content
Open
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
78 changes: 49 additions & 29 deletions crates/openshell-driver-mxc/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,12 +545,9 @@ impl MxcComputeBackend {
self.map_sandbox_policy(&sandbox.id, policy, egress_addr)?;
Ok(())
}
pub async fn get_sandbox(&self, sandbox_name: &str) -> Option<DriverSandbox> {
pub async fn get_sandbox(&self, sandbox_id: &str) -> Option<DriverSandbox> {
let registry = self.registry.lock().await;
registry
.values()
.find(|e| e.sandbox.name == sandbox_name)
.map(|e| e.sandbox.clone())
registry.get(sandbox_id).map(|e| e.sandbox.clone())
}

pub async fn list_sandboxes(&self) -> Vec<DriverSandbox> {
Expand Down Expand Up @@ -661,23 +658,20 @@ impl MxcComputeBackend {

Ok(())
}
pub async fn stop_sandbox(&self, sandbox_name: &str) -> Result<(), tonic::Status> {
let (sandbox_id, lifecycle_gate) = {
pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), tonic::Status> {
let lifecycle_gate = {
let registry = self.registry.lock().await;
let entry = registry
.values()
.find(|entry| entry.sandbox.name == sandbox_name)
.ok_or_else(|| {
tonic::Status::not_found(format!("sandbox {sandbox_name} not found"))
})?;
(entry.sandbox.id.clone(), entry.lifecycle_gate.clone())
let entry = registry.get(sandbox_id).ok_or_else(|| {
tonic::Status::not_found(format!("sandbox {sandbox_id} not found"))
})?;
entry.lifecycle_gate.clone()
};

let _lifecycle_guard = lifecycle_gate.lock().await;
let (iso_id, mut isolation_stopped, cancel, monitor_task) = {
let mut registry = self.registry.lock().await;
let entry = registry.get_mut(&sandbox_id).ok_or_else(|| {
tonic::Status::not_found(format!("sandbox {sandbox_name} not found"))
let entry = registry.get_mut(sandbox_id).ok_or_else(|| {
tonic::Status::not_found(format!("sandbox {sandbox_id} not found"))
})?;
(
entry.iso_sandbox_id.clone(),
Expand All @@ -704,7 +698,7 @@ impl MxcComputeBackend {
}

let mut registry = self.registry.lock().await;
if let Some(entry) = registry.get_mut(&sandbox_id) {
if let Some(entry) = registry.get_mut(sandbox_id) {
entry.isolation_stopped = isolation_stopped;
entry.host_proxy = None;
entry.phase_state = PhaseState::Stopped;
Expand All @@ -725,21 +719,12 @@ impl MxcComputeBackend {
}
Ok(())
}
pub async fn delete_sandbox(
&self,
sandbox_id: &str,
sandbox_name: &str,
) -> Result<bool, tonic::Status> {
pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result<bool, tonic::Status> {
let lifecycle_gate = {
let registry = self.registry.lock().await;
let Some(entry) = registry.get(sandbox_id) else {
return Ok(false);
};
if entry.sandbox.name != sandbox_name {
return Err(tonic::Status::failed_precondition(
"sandbox_id did not match sandbox_name",
));
}
entry.lifecycle_gate.clone()
};

Expand Down Expand Up @@ -1340,14 +1325,14 @@ mod lifecycle_tests {
/// Poll the backend registry until the predicate matches or the deadline hits.
async fn wait_for<F>(
backend: &MxcComputeBackend,
name: &str,
id: &str,
mut pred: F,
) -> Option<DriverSandbox>
where
F: FnMut(&DriverSandbox) -> bool,
{
for _ in 0..100 {
if let Some(sandbox) = backend.get_sandbox(name).await
if let Some(sandbox) = backend.get_sandbox(id).await
&& pred(&sandbox)
{
return Some(sandbox);
Expand Down Expand Up @@ -1778,6 +1763,41 @@ mod lifecycle_tests {
assert_eq!(ready_condition(&stopped).unwrap().reason, "Stopped");
}

#[tokio::test]
async fn lifecycle_selects_only_the_requested_id_when_names_collide() {
let tmp = tempfile::tempdir().unwrap();
let share = tmp.path().to_string_lossy().replace('\\', "/");
let backend = MxcComputeBackend::new_mocked(host_grants_config());
for (id, workspace) in [("sb-ws-a", "workspace-a"), ("sb-ws-b", "workspace-b")] {
let command = vec![
"powershell".into(),
"-NoProfile".into(),
"-Command".into(),
format!("$null = '{share}'; Start-Sleep -Seconds 60"),
];
let mut sandbox = with_policy(
driver_sandbox_with_command(id, "", command),
fs_policy(&[&share]),
);
sandbox.name = "shared-name".to_string();
sandbox.workspace = workspace.to_string();
backend
.create_sandbox(&sandbox)
.await
.expect("create accepted");
}

assert_eq!(backend.get_sandbox("sb-ws-a").await.unwrap().id, "sb-ws-a");
assert_eq!(backend.get_sandbox("sb-ws-b").await.unwrap().id, "sb-ws-b");
assert!(backend.get_sandbox("shared-name").await.is_none());

assert!(!backend.delete_sandbox("shared-name").await.unwrap());
assert!(backend.delete_sandbox("sb-ws-a").await.unwrap());
assert!(backend.get_sandbox("sb-ws-a").await.is_none());
assert!(backend.get_sandbox("sb-ws-b").await.is_some());
backend.delete_sandbox("sb-ws-b").await.unwrap();
}

#[tokio::test]
async fn unmappable_network_policy_fails_create_lifecycle() {
use openshell_core::proto::{NetworkEndpoint, NetworkPolicyRule};
Expand Down
62 changes: 43 additions & 19 deletions crates/openshell-driver-mxc/src/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,14 @@ impl ComputeDriver for ComputeDriverService {
request: Request<GetSandboxRequest>,
) -> Result<Response<GetSandboxResponse>, Status> {
let req = request.into_inner();
if req.name.is_empty() {
return Err(Status::invalid_argument("name is required"));
if req.sandbox_id.is_empty() {
return Err(Status::invalid_argument("sandbox_id is required"));
}
let sandbox = self
.backend
.get_sandbox(&req.name)
.get_sandbox(&req.sandbox_id)
.await
.ok_or_else(|| Status::not_found(format!("sandbox {} not found", req.name)))?;
if !req.sandbox_id.is_empty() && req.sandbox_id != sandbox.id {
return Err(Status::failed_precondition(
"sandbox_id did not match the fetched sandbox",
));
}
.ok_or_else(|| Status::not_found(format!("sandbox {} not found", req.sandbox_id)))?;
Ok(Response::new(GetSandboxResponse {
sandbox: Some(sandbox),
}))
Expand Down Expand Up @@ -130,10 +125,10 @@ impl ComputeDriver for ComputeDriverService {
request: Request<StopSandboxRequest>,
) -> Result<Response<StopSandboxResponse>, Status> {
let req = request.into_inner();
if req.name.is_empty() {
return Err(Status::invalid_argument("name is required"));
if req.sandbox_id.is_empty() {
return Err(Status::invalid_argument("sandbox_id is required"));
}
self.backend.stop_sandbox(&req.name).await?;
self.backend.stop_sandbox(&req.sandbox_id).await?;
Ok(Response::new(StopSandboxResponse {}))
}

Expand All @@ -154,13 +149,7 @@ impl ComputeDriver for ComputeDriverService {
if req.sandbox_id.is_empty() {
return Err(Status::invalid_argument("sandbox_id is required"));
}
if req.name.is_empty() {
return Err(Status::invalid_argument("name is required"));
}
let deleted = self
.backend
.delete_sandbox(&req.sandbox_id, &req.name)
.await?;
let deleted = self.backend.delete_sandbox(&req.sandbox_id).await?;
Ok(Response::new(DeleteSandboxResponse { deleted }))
}

Expand Down Expand Up @@ -228,6 +217,41 @@ mod tests {
assert!(error.message().contains("does not authenticate"));
}

#[tokio::test]
async fn lifecycle_requests_require_a_sandbox_id() {
let service = ComputeDriverService::new(MxcComputeBackend::new(
openshell_core::config::DEFAULT_GATEWAY_NAME,
MxcComputeConfig::default(),
));

let get = service
.get_sandbox(Request::new(GetSandboxRequest {
name: "legacy-name".into(),
..Default::default()
}))
.await
.expect_err("an empty sandbox_id must be rejected");
assert_eq!(get.code(), tonic::Code::InvalidArgument);

let stop = service
.stop_sandbox(Request::new(StopSandboxRequest {
name: "legacy-name".into(),
..Default::default()
}))
.await
.expect_err("an empty sandbox_id must be rejected");
assert_eq!(stop.code(), tonic::Code::InvalidArgument);

let delete = service
.delete_sandbox(Request::new(DeleteSandboxRequest {
name: "legacy-name".into(),
..Default::default()
}))
.await
.expect_err("an empty sandbox_id must be rejected");
assert_eq!(delete.code(), tonic::Code::InvalidArgument);
}

#[tokio::test]
async fn workspace_lifecycle_is_an_idempotent_no_op() {
let service = ComputeDriverService::new(MxcComputeBackend::new(
Expand Down
7 changes: 7 additions & 0 deletions docs/extensibility/drivers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ Refer to [Protocol Negotiation](/extensibility/overview#protocol-negotiation) fo
contract. Your driver must also acknowledge the gateway's
[resource admission policy](/how-it-works/gateways/configuration#external-resource-admission).

The gateway identifies a sandbox in `GetSandbox`, `StopSandbox`, `StartSandbox`,
and `DeleteSandbox` by its stable `sandbox_id` only. Reject an empty
`sandbox_id`, and do not look sandboxes up by name. The `name` field on these
requests is deprecated: the gateway still sends the stored name for drivers
that predate ID-only requests, but a driver must ignore it. `ListSandboxes` returns every sandbox
the driver manages, each with a non-empty `id` that is unique across workspaces.

Run your driver as a separate service listening on a Unix domain socket. The
gateway does not start or supervise it. Restrict socket access to the gateway
user and make the socket accessible from the gateway's host or container.
Expand Down
4 changes: 4 additions & 0 deletions proto/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ changing existing APIs; generated SDK naming follows from these definitions.
`driver_name`, `runtime_class_name`, `rule_name`, and `middleware_name`.
- Public callers reference entities by canonical name. Keep immutable IDs at
authentication, persistence, compute-driver, and other internal boundaries.
- Compute-driver sandbox lifecycle requests use the gateway-assigned
`sandbox_id` as their sole resource reference. `DriverSandbox.name` and
`DriverSandbox.workspace` are observation metadata and must not be used as
lookup keys by a driver.

For example:

Expand Down
38 changes: 29 additions & 9 deletions proto/compute_driver.proto
Original file line number Diff line number Diff line change
Expand Up @@ -465,9 +465,13 @@ message ValidateSandboxCreateRequest {
message ValidateSandboxCreateResponse {}

message GetSandboxRequest {
// Stable sandbox ID stored by the gateway.
// Required stable sandbox ID assigned by the gateway. This immutable ID is
// the sole sandbox reference at the compute-driver boundary.
string sandbox_id = 1;
// Compute-runtime name used by the driver.
// Deprecated. The gateway still sends the stored sandbox name so drivers that
// predate ID-only lifecycle requests keep working. Drivers must not use it to
// locate a sandbox. The gateway will stop sending it, and field 2 and the
// name `name` will be reserved, once no supported driver reads it.
string name = 2;
}

Expand Down Expand Up @@ -502,10 +506,14 @@ message SupervisorAppEndpoint {
uint64 ownership_epoch = 5;
}

// Requests the complete sandbox inventory managed by this configured driver
// instance. This collection is intentionally unscoped by workspace.
message ListSandboxesRequest {}

message ListSandboxesResponse {
// Platform-observed sandbox snapshots returned by the driver.
// Platform-observed sandbox snapshots returned by the driver. Every entry
// must carry a non-empty, globally unique DriverSandbox.id. Workspace and
// name are observation metadata, not collection keys.
repeated DriverSandbox sandboxes = 1;
}

Expand Down Expand Up @@ -541,18 +549,26 @@ message SandboxUpdatePreconditions {


message StopSandboxRequest {
// Stable sandbox ID stored by the gateway.
// Required stable sandbox ID assigned by the gateway. This immutable ID is
// the sole sandbox reference at the compute-driver boundary.
string sandbox_id = 1;
// Compute-runtime name used by the driver.
// Deprecated. The gateway still sends the stored sandbox name so drivers that
// predate ID-only lifecycle requests keep working. Drivers must not use it to
// locate a sandbox. The gateway will stop sending it, and field 2 and the
// name `name` will be reserved, once no supported driver reads it.
string name = 2;
}

message StopSandboxResponse {}

message StartSandboxRequest {
// Stable sandbox ID stored by the gateway.
// Required stable sandbox ID assigned by the gateway. This immutable ID is
// the sole sandbox reference at the compute-driver boundary.
string sandbox_id = 1;
// Compute-runtime name used by the driver.
// Deprecated. The gateway still sends the stored sandbox name so drivers that
// predate ID-only lifecycle requests keep working. Drivers must not use it to
// locate a sandbox. The gateway will stop sending it, and field 2 and the
// name `name` will be reserved, once no supported driver reads it.
string name = 2;
// Fresh launch credentials for start-from-stopped. Empty only for drivers
// that do not implement the OpenShell Sandbox Protocol.
Expand Down Expand Up @@ -602,9 +618,13 @@ message StartSandboxResponse {
}

message DeleteSandboxRequest {
// Stable sandbox ID stored by the gateway.
// Required stable sandbox ID assigned by the gateway. This immutable ID is
// the sole sandbox reference at the compute-driver boundary.
string sandbox_id = 1;
// Compute-runtime name used by the driver.
// Deprecated. The gateway still sends the stored sandbox name so drivers that
// predate ID-only lifecycle requests keep working. Drivers must not use it to
// locate a sandbox. The gateway will stop sending it, and field 2 and the
// name `name` will be reserved, once no supported driver reads it.
string name = 2;
}

Expand Down
Loading