Skip to content

Commit 7e10ae3

Browse files
committed
feat(isolation): add supervisor-owned boundary cleanup
Signed-off-by: Drew Newberry <385+drew@users.noreply.github.com>
1 parent f141d7f commit 7e10ae3

4 files changed

Lines changed: 258 additions & 40 deletions

File tree

‎crates/openshell-driver-docker/src/isolation.rs‎

Lines changed: 158 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -247,21 +247,45 @@ impl IsolationBackend for DockerIsolationBackend {
247247
Ok(CreatedBoundary::new(descriptor, Box::new(bound)))
248248
}
249249

250+
async fn destroy(
251+
&self,
252+
descriptor: VerifiedTopologyDescriptor,
253+
sandbox_id: &str,
254+
) -> Result<(), BackendError> {
255+
let topology = decode_topology(&descriptor)?;
256+
validate_topology_identity(&topology, sandbox_id, &self.listener_dir)?;
257+
258+
let inspected = match self
259+
.docker
260+
.inspect_container(&topology.container_id, None)
261+
.await
262+
{
263+
Ok(inspected) => Some(inspected),
264+
Err(BollardError::DockerResponseServerError {
265+
status_code: 404, ..
266+
}) => None,
267+
Err(error) => return Err(docker_error("inspect Docker boundary for destroy", error)),
268+
};
269+
if let Some(inspected) = inspected {
270+
validate_container_labels(
271+
&inspected,
272+
&topology.sandbox_id,
273+
&topology.launch_generation,
274+
&topology.plan_fingerprint,
275+
)?;
276+
remove_container(&self.docker, &topology.container_id).await?;
277+
}
278+
remove_listener_artifacts(&topology.listener_path)?;
279+
Ok(())
280+
}
281+
250282
async fn attach(
251283
&self,
252284
descriptor: VerifiedTopologyDescriptor,
253285
sandbox: SandboxContext,
254286
) -> Result<Box<dyn BoundBoundary>, BackendError> {
255-
let topology: DockerTopology =
256-
serde_json::from_slice(descriptor.payload()).map_err(|error| {
257-
BackendError::Descriptor(format!("decode Docker topology: {error}"))
258-
})?;
259-
if topology.sandbox_id != sandbox.sandbox_id {
260-
return Err(BackendError::Denied(format!(
261-
"Docker boundary sandbox {:?} does not match admitted sandbox {:?}",
262-
topology.sandbox_id, sandbox.sandbox_id
263-
)));
264-
}
287+
let topology = decode_topology(&descriptor)?;
288+
validate_topology_identity(&topology, &sandbox.sandbox_id, &self.listener_dir)?;
265289
let inspected = self
266290
.docker
267291
.inspect_container(&topology.container_id, None)
@@ -381,11 +405,68 @@ fn topology_descriptor(topology: &DockerTopology) -> Result<TopologyDescriptor,
381405
})
382406
}
383407

408+
fn decode_topology(
409+
descriptor: &VerifiedTopologyDescriptor,
410+
) -> Result<DockerTopology, BackendError> {
411+
serde_json::from_slice(descriptor.payload())
412+
.map_err(|error| BackendError::Descriptor(format!("decode Docker topology: {error}")))
413+
}
414+
415+
fn validate_topology_identity(
416+
topology: &DockerTopology,
417+
sandbox_id: &str,
418+
listener_dir: &Path,
419+
) -> Result<(), BackendError> {
420+
if topology.sandbox_id != sandbox_id {
421+
return Err(BackendError::Denied(format!(
422+
"Docker boundary sandbox {:?} does not match admitted sandbox {sandbox_id:?}",
423+
topology.sandbox_id
424+
)));
425+
}
426+
let key = resource_key(&topology.sandbox_id, &topology.launch_generation);
427+
let expected_name = format!("openshell-boundary-{key}");
428+
let expected_listener = listener_dir.join(format!("{key}.sock"));
429+
let expected_metadata_prefix = format!(
430+
"openshell:{}:{}:",
431+
topology.sandbox_id, topology.launch_generation
432+
);
433+
if topology.container_id.is_empty()
434+
|| topology.container_name != expected_name
435+
|| topology.listener_path != expected_listener
436+
|| !topology
437+
.listener_metadata
438+
.starts_with(&expected_metadata_prefix)
439+
|| topology.listener_metadata.len()
440+
< expected_metadata_prefix.len() + MIN_LISTENER_TOKEN_BYTES
441+
{
442+
return Err(BackendError::Denied(
443+
"Docker topology identity does not match its trusted resource key".to_string(),
444+
));
445+
}
446+
Ok(())
447+
}
448+
384449
fn validate_existing_container(
385450
inspected: &bollard::models::ContainerInspectResponse,
386451
sandbox_id: &str,
387452
launch_generation: &str,
388453
plan_fingerprint: &str,
454+
) -> Result<(), BackendError> {
455+
validate_container_labels(inspected, sandbox_id, launch_generation, plan_fingerprint)?;
456+
let status = inspected.state.as_ref().and_then(|state| state.status);
457+
if status != Some(ContainerStateStatusEnum::CREATED) {
458+
return Err(BackendError::Denied(format!(
459+
"Docker create/attach prototype requires a non-running container, found {status:?}"
460+
)));
461+
}
462+
Ok(())
463+
}
464+
465+
fn validate_container_labels(
466+
inspected: &bollard::models::ContainerInspectResponse,
467+
sandbox_id: &str,
468+
launch_generation: &str,
469+
plan_fingerprint: &str,
389470
) -> Result<(), BackendError> {
390471
let labels = inspected
391472
.config
@@ -401,11 +482,42 @@ fn validate_existing_container(
401482
"existing Docker boundary does not match sandbox launch generation".to_string(),
402483
));
403484
}
404-
let status = inspected.state.as_ref().and_then(|state| state.status);
405-
if status != Some(ContainerStateStatusEnum::CREATED) {
406-
return Err(BackendError::Denied(format!(
407-
"Docker create/attach prototype requires a non-running container, found {status:?}"
408-
)));
485+
Ok(())
486+
}
487+
488+
async fn remove_container(docker: &Docker, container_id: &str) -> Result<(), BackendError> {
489+
if let Err(error) = docker
490+
.remove_container(
491+
container_id,
492+
Some(RemoveContainerOptionsBuilder::default().force(true).build()),
493+
)
494+
.await
495+
&& !matches!(
496+
error,
497+
BollardError::DockerResponseServerError {
498+
status_code: 404,
499+
..
500+
}
501+
)
502+
{
503+
return Err(docker_error("remove Docker boundary", error));
504+
}
505+
Ok(())
506+
}
507+
508+
fn remove_listener_artifacts(listener_path: &Path) -> Result<(), BackendError> {
509+
for path in [
510+
listener_path.to_path_buf(),
511+
listener_path.with_extension("lock"),
512+
] {
513+
if let Err(error) = std::fs::remove_file(&path)
514+
&& error.kind() != std::io::ErrorKind::NotFound
515+
{
516+
return Err(BackendError::Attach(format!(
517+
"remove Docker listener artifact {}: {error}",
518+
path.display()
519+
)));
520+
}
409521
}
410522
Ok(())
411523
}
@@ -665,24 +777,7 @@ impl BoundaryProcess for DockerProcess {
665777
}
666778

667779
async fn terminate(&self) -> Result<(), BackendError> {
668-
if let Err(error) = self
669-
.docker
670-
.remove_container(
671-
&self.container_id,
672-
Some(RemoveContainerOptionsBuilder::default().force(true).build()),
673-
)
674-
.await
675-
&& !matches!(
676-
error,
677-
BollardError::DockerResponseServerError {
678-
status_code: 404,
679-
..
680-
}
681-
)
682-
{
683-
return Err(docker_error("remove Docker boundary", error));
684-
}
685-
Ok(())
780+
remove_container(&self.docker, &self.container_id).await
686781
}
687782
}
688783

@@ -991,6 +1086,30 @@ mod tests {
9911086
);
9921087
}
9931088

1089+
#[test]
1090+
fn topology_identity_pins_cleanup_to_the_backend_listener_directory() {
1091+
let listener_dir = tempfile::tempdir().expect("listener tempdir");
1092+
let key = resource_key("sandbox-1", "generation-1");
1093+
let topology = DockerTopology {
1094+
sandbox_id: "sandbox-1".to_string(),
1095+
launch_generation: "generation-1".to_string(),
1096+
container_id: "container-id".to_string(),
1097+
container_name: format!("openshell-boundary-{key}"),
1098+
listener_path: listener_dir.path().join(format!("{key}.sock")),
1099+
listener_metadata: format!(
1100+
"openshell:sandbox-1:generation-1:{}",
1101+
"0".repeat(MIN_LISTENER_TOKEN_BYTES)
1102+
),
1103+
plan_fingerprint: "fingerprint".to_string(),
1104+
};
1105+
validate_topology_identity(&topology, "sandbox-1", listener_dir.path())
1106+
.expect("matching topology");
1107+
1108+
let mut escaped = topology;
1109+
escaped.listener_path = listener_dir.path().join("../outside.sock");
1110+
assert!(validate_topology_identity(&escaped, "sandbox-1", listener_dir.path()).is_err());
1111+
}
1112+
9941113
#[tokio::test]
9951114
#[ignore = "requires a local Linux Docker daemon, runc seccomp-notify support, and a pre-pulled image"]
9961115
async fn local_docker_denies_notified_uname_without_in_container_supervisor() {
@@ -1033,6 +1152,11 @@ mod tests {
10331152
.expect("uname should not remain blocked")
10341153
.expect("observe uname exit");
10351154
assert!(matches!(status, BoundaryExitStatus::Exited(code) if code != 0));
1036-
process.terminate().await.expect("remove Docker boundary");
1155+
drop(process);
1156+
drop(running);
1157+
registry
1158+
.destroy_created(descriptor, origin, BACKEND_NAME, "sandbox-1")
1159+
.await
1160+
.expect("destroy supervisor-created Docker boundary");
10371161
}
10381162
}

‎crates/openshell-isolation/src/contract.rs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,34 @@ impl BackendRegistry {
470470
}
471471
}
472472
}
473+
474+
/// Destroy a resource created by the supervisor through this registry.
475+
///
476+
/// Trusted durable state supplies `origin`; externally created resources
477+
/// remain owned by their compute driver or orchestrator and are rejected.
478+
/// Destruction is idempotent at the backend-specific resource layer.
479+
///
480+
/// # Errors
481+
///
482+
/// Returns [`BackendError::Denied`] when `origin` is not
483+
/// [`BoundaryOrigin::SupervisorCreated`], an envelope resolution error, or
484+
/// the selected backend's destruction error.
485+
pub async fn destroy_created(
486+
&self,
487+
descriptor: TopologyDescriptor,
488+
origin: BoundaryOrigin,
489+
admitted_backend_name: &str,
490+
sandbox_id: &str,
491+
) -> Result<(), BackendError> {
492+
if origin != BoundaryOrigin::SupervisorCreated {
493+
return Err(BackendError::Denied(
494+
"the supervisor cannot destroy an externally created isolation resource"
495+
.to_string(),
496+
));
497+
}
498+
let (backend, verified) = self.resolve(descriptor, admitted_backend_name)?;
499+
backend.destroy(verified, sandbox_id).await
500+
}
473501
}
474502

475503
/// A fresh supervisor-created resource already bound to its admitted sandbox.
@@ -554,6 +582,22 @@ pub trait IsolationBackend: Send + Sync {
554582
)))
555583
}
556584

585+
/// Destroy a resource previously returned by [`Self::create`].
586+
///
587+
/// This operation is optional for attach-only backends. Implementations
588+
/// must validate the descriptor against `sandbox_id` and make retries
589+
/// idempotent so recovery can finish cleanup after a supervisor crash.
590+
async fn destroy(
591+
&self,
592+
_descriptor: VerifiedTopologyDescriptor,
593+
_sandbox_id: &str,
594+
) -> Result<(), BackendError> {
595+
Err(BackendError::Unsupported(format!(
596+
"backend {:?} does not support supervisor-owned destruction",
597+
self.backend_name()
598+
)))
599+
}
600+
557601
/// Validate the opaque payload and atomically bind it to the trusted
558602
/// sandbox context: returns `Bound` or fails closed. Never binds a resource
559603
/// that is already bound to an active boundary.

‎crates/openshell-isolation/src/contract/tests.rs‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,9 @@ impl IsolationBackend for WrongVersionBackend {
286286

287287
/// A backend that opts into supervisor-owned creation. The ordinary mock
288288
/// backends intentionally rely on the trait's attach-only default.
289-
struct CreatingBackend;
289+
struct CreatingBackend {
290+
destroyed: Arc<AtomicBool>,
291+
}
290292

291293
#[async_trait]
292294
impl IsolationBackend for CreatingBackend {
@@ -318,6 +320,17 @@ impl IsolationBackend for CreatingBackend {
318320
))
319321
}
320322

323+
async fn destroy(
324+
&self,
325+
descriptor: VerifiedTopologyDescriptor,
326+
sandbox_id: &str,
327+
) -> Result<(), BackendError> {
328+
assert_eq!(descriptor.backend_name(), self.backend_name());
329+
assert_eq!(descriptor.payload(), sandbox_id.as_bytes());
330+
self.destroyed.store(true, Ordering::SeqCst);
331+
Ok(())
332+
}
333+
321334
async fn attach(
322335
&self,
323336
descriptor: VerifiedTopologyDescriptor,
@@ -488,8 +501,11 @@ async fn attach_only_backend_may_omit_create() {
488501
#[tokio::test]
489502
async fn create_and_attach_converge_on_the_same_lifecycle() {
490503
let mut reg = BackendRegistry::new();
491-
reg.register(Arc::new(CreatingBackend))
492-
.expect("register creating backend");
504+
let destroyed = Arc::new(AtomicBool::new(false));
505+
reg.register(Arc::new(CreatingBackend {
506+
destroyed: destroyed.clone(),
507+
}))
508+
.expect("register creating backend");
493509

494510
let (descriptor, created) = drive_create(&reg, create_plan("mock-creating"), "mock-creating")
495511
.await
@@ -499,13 +515,38 @@ async fn create_and_attach_converge_on_the_same_lifecycle() {
499515
BoundaryExitStatus::Exited(0)
500516
);
501517

502-
let attached = drive(&reg, descriptor, "mock-creating")
518+
let attached = drive(&reg, descriptor.clone(), "mock-creating")
503519
.await
504520
.expect("attach lifecycle");
505521
assert_eq!(
506522
attached.agent().wait().await.expect("attached agent wait"),
507523
BoundaryExitStatus::Exited(0)
508524
);
525+
526+
reg.destroy_created(
527+
descriptor,
528+
BoundaryOrigin::SupervisorCreated,
529+
"mock-creating",
530+
"sb-1",
531+
)
532+
.await
533+
.expect("destroy supervisor-created resource");
534+
assert!(destroyed.load(Ordering::SeqCst));
535+
}
536+
537+
#[tokio::test]
538+
async fn registry_never_destroys_an_externally_created_resource() {
539+
let reg = registry();
540+
let error = reg
541+
.destroy_created(
542+
descriptor("mock-primary"),
543+
BoundaryOrigin::ExternallyCreated,
544+
"mock-primary",
545+
"sb-1",
546+
)
547+
.await
548+
.expect_err("external lifecycle owner must retain destruction authority");
549+
assert!(matches!(error, BackendError::Denied(_)));
509550
}
510551

511552
#[test]

0 commit comments

Comments
 (0)