1 //! The container boundary: a plugin in a sibling container connects to a2 //! private filesystem socket, receives a descriptor, and finishes a job.3 //!4 //! The test needs Docker and an image with a shell and python3. It is skipped5 //! when Docker or the image is unavailable. Set `INF3R_TEST_IMAGE` to use an6 //! image other than `inf3r:local`; set `INF3R_TEST_TOY` to the host path of7 //! `inf3r-toy-x64-cpu`.8 9 use std::fs::{self, File};10 use std::os::fd::AsFd;11 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};12 use std::path::{Path, PathBuf};13 use std::process::{Child, Command, Stdio};14 use std::sync::atomic::{AtomicU64, Ordering};15 use std::time::Duration;16 17 use inf3r_proto::Value;18 use inf3r_proto::body::{self, Dependency, Grant, Open, PartKind};19 use inf3r_proto::client::{Item, Peer};20 use inf3r_supervisor::{Listener, SpawnError};21 22 const WAIT: Duration = Duration::from_secs(20);23 const IMAGE: &str = "inf3r:local";24 25 /// The Docker command with the rootless socket when the environment is bare.26 /// The target directory used by this cargo invocation.27 fn target_dir() -> std::path::PathBuf {28 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");29 match std::env::var_os("CARGO_TARGET_DIR") {30 Some(dir) => {31 let dir = std::path::PathBuf::from(dir);32 if dir.is_absolute() {33 dir34 } else {35 root.join(dir)36 }37 }38 None => root.join("target"),39 }40 }41 42 fn docker() -> Command {43 let mut command = Command::new("docker");44 if std::env::var_os("DOCKER_HOST").is_none() {45 let uid = rustix::process::geteuid().as_raw();46 let socket = format!("/run/user/{uid}/docker.sock");47 if Path::new(&socket).exists() {48 command.env("DOCKER_HOST", format!("unix://{socket}"));49 }50 }51 command52 }53 54 /// A container that is removed even when the test panics.55 struct Docker {56 child: Child,57 name: String,58 }59 60 impl Drop for Docker {61 fn drop(&mut self) {62 let _ = self.child.kill();63 let _ = self.child.wait();64 let _ = docker()65 .args(["rm", "-f", &self.name])66 .stdout(Stdio::null())67 .stderr(Stdio::null())68 .status();69 }70 }71 72 fn next() -> u64 {73 static NEXT: AtomicU64 = AtomicU64::new(1);74 NEXT.fetch_add(1, Ordering::Relaxed)75 }76 77 fn container_running(name: &str) -> bool {78 docker()79 .args(["inspect", "-f", "{{.State.Running}}", name])80 .output()81 .ok()82 .filter(|output| output.status.success())83 .map(|output| String::from_utf8_lossy(&output.stdout).trim() == "true")84 .unwrap_or(false)85 }86 87 fn docker_cli_pid(name: &str) -> Option<u32> {88 for entry in fs::read_dir("/proc").ok()? {89 let entry = entry.ok()?;90 let Ok(pid) = entry.file_name().to_string_lossy().parse::<u32>() else {91 continue;92 };93 let Ok(bytes) = fs::read(entry.path().join("cmdline")) else {94 continue;95 };96 let text = String::from_utf8_lossy(&bytes);97 if text.contains("docker") && text.contains(&format!("--name\0{name}\0")) {98 return Some(pid);99 }100 }101 None102 }103 104 fn image() -> String {105 std::env::var("INF3R_TEST_IMAGE").unwrap_or_else(|_| IMAGE.to_string())106 }107 108 fn toy() -> PathBuf {109 std::env::var_os("INF3R_TEST_TOY")110 .map(PathBuf::from)111 .unwrap_or_else(|| target_dir().join("debug/inf3r-toy-x64-cpu"))112 }113 114 fn available() -> bool {115 let image = image();116 let status = docker()117 .args(["image", "inspect", &image])118 .stdout(Stdio::null())119 .stderr(Stdio::null())120 .status();121 if !status.is_ok_and(|status| status.success()) {122 eprintln!("container test skipped: image {image} is missing");123 return false;124 }125 if !toy().is_file() {126 eprintln!("container test skipped: {} is missing", toy().display());127 return false;128 }129 true130 }131 132 fn run(name: &str, dir: &Path, program: &str, args: &[String]) -> Docker {133 let image = image();134 let mut command = docker();135 command136 .arg("run")137 .arg("--rm")138 .arg("--name")139 .arg(name)140 .args(["--user", "0:0"])141 .args(["--network", "none"])142 .arg("--read-only")143 .args(["--tmpfs", "/tmp"])144 .args(["--cap-drop", "ALL"])145 .args(["--security-opt", "no-new-privileges"])146 .arg("-v")147 .arg(format!("{}:{}:rw", dir.display(), dir.display()))148 .arg("-v")149 .arg(format!("{}:/opt/inf3r/bin/plugin:ro", toy().display()))150 .args(["--entrypoint", program])151 .arg(image)152 .args(args)153 .stdout(Stdio::null())154 .stderr(Stdio::null());155 let child = command.spawn().expect("docker run");156 Docker {157 child,158 name: name.to_string(),159 }160 }161 162 fn grant(path: &Path) -> (Grant, File) {163 let file = File::open(path).expect("the weight file");164 let len = file.metadata().expect("metadata").len();165 (166 Grant {167 deps: vec![Dependency {168 role: "weights".into(),169 fd: 0,170 len,171 path: String::new(),172 }],173 },174 file,175 )176 }177 178 /// A tiny valid GGUF: vocabulary `["x", "a"]`, stop `zzz`.179 fn weights() -> PathBuf {180 fn push_str(out: &mut Vec<u8>, text: &str) {181 out.extend_from_slice(&(text.len() as u64).to_le_bytes());182 out.extend_from_slice(text.as_bytes());183 }184 let vocab = ["x", "a"];185 let stop = "zzz";186 let mut out = Vec::new();187 out.extend_from_slice(b"GGUF");188 out.extend_from_slice(&3u32.to_le_bytes());189 out.extend_from_slice(&1u64.to_le_bytes());190 out.extend_from_slice(&2u64.to_le_bytes());191 push_str(&mut out, "toy.vocab");192 out.extend_from_slice(&12u32.to_le_bytes());193 out.extend_from_slice(&11u32.to_le_bytes());194 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());195 for token in vocab {196 push_str(&mut out, token);197 }198 push_str(&mut out, "toy.stop");199 out.extend_from_slice(&11u32.to_le_bytes());200 push_str(&mut out, stop);201 push_str(&mut out, "embed");202 out.extend_from_slice(&2u32.to_le_bytes());203 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());204 out.extend_from_slice(&8u64.to_le_bytes());205 out.extend_from_slice(&0u32.to_le_bytes());206 out.extend_from_slice(&0u64.to_le_bytes());207 let rem = out.len() % 32;208 if rem != 0 {209 out.resize(out.len() + (32 - rem), 0);210 }211 for token in 0..vocab.len() {212 for position in 0..8 {213 let value = if token == 1 && position == 0 {214 1.0f32215 } else {216 0.0f32217 };218 out.extend_from_slice(&value.to_le_bytes());219 }220 }221 let path = Path::new("/tmp").join(format!("inf3r-container-weight-{}.gguf", next()));222 fs::write(&path, out).expect("write the generated GGUF");223 path224 }225 226 #[test]227 fn a_container_peer_connects_receives_a_descriptor_and_finishes_a_job() {228 if !available() {229 return;230 }231 let root = Path::new("/tmp").join(format!("inf3r-container-test-{}", std::process::id()));232 fs::DirBuilder::new()233 .recursive(true)234 .mode(0o700)235 .create(&root)236 .expect("the run root");237 let listener = Listener::bind(&root).expect("bind");238 let socket = listener.path().to_string_lossy().into_owned();239 let instance = listener.directory().to_path_buf();240 let name = format!("inf3r-container-{}", next());241 let container = run(242 &name,243 &instance,244 "/opt/inf3r/bin/plugin",245 &["--socket".into(), socket],246 );247 248 let stream = listener249 .accept(WAIT, rustix::process::geteuid().as_raw())250 .expect("the container connects");251 stream.set_nonblocking(false).expect("blocking");252 let peer = Peer::connect(stream, "container-test", WAIT).expect("handshake");253 let catalogue = peer.catalogue().expect("catalogue");254 let model = catalogue255 .models256 .iter()257 .find(|model| model.capabilities.contains_key("chat"))258 .expect("a chat model")259 .serve260 .clone();261 let path = weights();262 let (grant, file) = grant(&path);263 peer.load_fds(&grant, &[file.as_fd()], WAIT).expect("load");264 let open = Open {265 request_id: "container-1".into(),266 model,267 capability: "chat".into(),268 credit: 1 << 20,269 budget_ms: 10_000,270 parts: vec![body::Part {271 kind: PartKind::Text,272 mime: "text/plain; charset=utf-8".into(),273 role: None,274 len: 1,275 hold: body::Hold::Inline(b"A".to_vec()),276 }],277 params: Value::Map(Vec::new()),278 };279 let mut job = peer.open(open, &[]).expect("open");280 loop {281 match job.next().expect("read").expect("an item") {282 Item::Accepted(_) | Item::Event { .. } => {}283 Item::Done(done, _) => {284 assert_eq!(done.outcome, body::Outcome::Completed);285 break;286 }287 Item::Reject(refusal) => panic!("refused: {refusal:?}"),288 }289 }290 drop(job);291 peer.close().expect("close");292 drop(container);293 drop(listener);294 let _ = fs::remove_file(path);295 let _ = fs::remove_dir_all(root);296 }297 298 #[test]299 fn a_wrong_uid_is_rejected_even_when_it_can_reach_the_directory() {300 if !available() {301 return;302 }303 let root = Path::new("/tmp").join(format!("inf3r-container-uid-{}", std::process::id()));304 fs::DirBuilder::new()305 .recursive(true)306 .mode(0o700)307 .create(&root)308 .expect("the run root");309 let listener = Listener::bind(&root).expect("bind");310 let instance = listener.directory().to_path_buf();311 // Make the boundary reachable so that the check under test is the peer uid,312 // not the directory mode. The production mode is 0700.313 fs::set_permissions(&instance, fs::Permissions::from_mode(0o755)).expect("directory mode");314 fs::set_permissions(listener.path(), fs::Permissions::from_mode(0o666)).expect("socket mode");315 let socket = listener.path().to_string_lossy().into_owned();316 let name = format!("inf3r-container-uid-{}", next());317 let mut command = docker();318 command319 .arg("run")320 .arg("--rm")321 .arg("--name")322 .arg(&name)323 .args(["--user", "1000:1000"])324 .args(["--network", "none"])325 .arg("--read-only")326 .args(["--tmpfs", "/tmp"])327 .args(["--cap-drop", "ALL"])328 .args(["--security-opt", "no-new-privileges"])329 .arg("-v")330 .arg(format!("{}:{}:rw", instance.display(), instance.display()))331 .args(["--entrypoint", "python3"])332 .arg(image())333 .arg("-c")334 .arg("import socket,sys; s=socket.socket(socket.AF_UNIX); s.connect(sys.argv[1])")335 .arg(&socket)336 .stdout(Stdio::null())337 .stderr(Stdio::null());338 let mut wrong = command.spawn().expect("docker run");339 let error = listener340 .accept(341 Duration::from_millis(500),342 rustix::process::geteuid().as_raw(),343 )344 .expect_err("a foreign uid must not be accepted");345 match error {346 SpawnError::Io(why) => assert!(why.contains("uid"), "{why}"),347 other => panic!("expected Io, got {other:?}"),348 }349 let _ = wrong.kill();350 let _ = wrong.wait();351 let _ = docker()352 .args(["rm", "-f", &name])353 .stdout(Stdio::null())354 .stderr(Stdio::null())355 .status();356 let _ = fs::remove_dir_all(root);357 }358 359 #[test]360 fn a_sibling_container_cannot_see_the_private_directory() {361 if !available() {362 return;363 }364 let root = Path::new("/tmp").join(format!("inf3r-container-sib-{}", std::process::id()));365 fs::DirBuilder::new()366 .recursive(true)367 .mode(0o700)368 .create(&root)369 .expect("the run root");370 let first = Listener::bind(&root).expect("first");371 let second = Listener::bind(&root).expect("second");372 let socket = first.path().to_string_lossy().into_owned();373 let name = format!("inf3r-container-sib-{}", next());374 let mut command = docker();375 command376 .arg("run")377 .arg("--rm")378 .arg("--name")379 .arg(&name)380 .args(["--user", "0:0"])381 .args(["--network", "none"])382 .arg("--read-only")383 .args(["--tmpfs", "/tmp"])384 .args(["--cap-drop", "ALL"])385 .args(["--security-opt", "no-new-privileges"])386 .arg("-v")387 .arg(format!(388 "{}:{}:rw",389 second.directory().display(),390 second.directory().display()391 ))392 .args(["--entrypoint", "sh"])393 .arg(image())394 .arg("-c")395 .arg(format!("test ! -e {socket}"))396 .stdout(Stdio::null())397 .stderr(Stdio::null());398 let status = command.status().expect("docker run");399 assert!(status.success(), "the sibling could see the first socket");400 drop(first);401 drop(second);402 let _ = fs::remove_dir_all(root);403 }404 405 #[test]406 fn a_container_can_restart_on_a_fresh_private_path() {407 if !available() {408 return;409 }410 let root = Path::new("/tmp").join(format!("inf3r-container-restart-{}", std::process::id()));411 fs::DirBuilder::new()412 .recursive(true)413 .mode(0o700)414 .create(&root)415 .expect("the run root");416 417 let first = Listener::bind(&root).expect("first");418 let first_socket = first.path().to_string_lossy().into_owned();419 let first_name = format!("inf3r-container-restart-a-{}", next());420 let first_container = run(421 &first_name,422 first.directory(),423 "/opt/inf3r/bin/plugin",424 &["--socket".into(), first_socket.clone()],425 );426 let stream = first427 .accept(WAIT, rustix::process::geteuid().as_raw())428 .expect("the first container connects");429 let peer = Peer::connect(stream, "restart-a", WAIT).expect("first handshake");430 drop(peer);431 drop(first_container);432 drop(first);433 434 let second = Listener::bind(&root).expect("second");435 let second_socket = second.path().to_string_lossy().into_owned();436 assert_ne!(first_socket, second_socket);437 let second_name = format!("inf3r-container-restart-b-{}", next());438 let _second_container = run(439 &second_name,440 second.directory(),441 "/opt/inf3r/bin/plugin",442 &["--socket".into(), second_socket],443 );444 let stream = second445 .accept(WAIT, rustix::process::geteuid().as_raw())446 .expect("the second container connects");447 let peer = Peer::connect(stream, "restart-b", WAIT).expect("second handshake");448 drop(peer);449 drop(second);450 let _ = fs::remove_dir_all(root);451 }452 453 #[test]454 fn a_supervised_container_exposes_its_host_pid_and_stops_cleanly() {455 if !available() {456 return;457 }458 let root = Path::new("/tmp").join(format!("inf3r-container-child-{}", std::process::id()));459 fs::DirBuilder::new()460 .recursive(true)461 .mode(0o700)462 .create(&root)463 .expect("the run root");464 let mut spec = inf3r_container::ContainerSpec::new(image(), "supervised");465 spec.command = vec!["/opt/inf3r/bin/plugin".into()];466 spec.mounts.push(inf3r_container::Mount {467 source: toy(),468 target: PathBuf::from("/opt/inf3r/bin/plugin"),469 read_only: true,470 });471 let mut child = inf3r_supervisor::Child::spawn_container_in(spec, &root)472 .expect("the supervisor starts a container");473 let stream = child.accept(WAIT).expect("the container connects");474 let peer = Peer::connect(stream, "supervised", WAIT).expect("handshake");475 let catalogue = peer.catalogue().expect("catalogue");476 assert!(477 catalogue478 .models479 .iter()480 .any(|model| model.capabilities.contains_key("chat"))481 );482 let pid = child.host_pid().expect("the container has a host pid");483 assert!(pid > 0);484 drop(peer);485 let name = child.container_name().expect("a container child");486 let stop = child.stop(Duration::from_secs(5)).expect("stop");487 assert!(!child.alive());488 assert!(stop.code.is_some() || stop.signal.is_some());489 // The listener directory is gone, and the container is not left behind.490 let listed = docker()491 .args([492 "ps",493 "-a",494 "--filter",495 &format!("name={name}"),496 "--format",497 "{{.Names}}",498 ])499 .output()500 .expect("docker ps");501 assert!(502 !String::from_utf8_lossy(&listed.stdout).contains(&name),503 "the container survived stop: {name}"504 );505 let _ = fs::remove_dir_all(root);506 }507 508 #[test]509 fn stopping_a_container_after_its_cli_exited_still_removes_the_container() {510 if !available() {511 return;512 }513 let root = Path::new("/tmp").join(format!("inf3r-container-cli-{}", std::process::id()));514 fs::DirBuilder::new()515 .recursive(true)516 .mode(0o700)517 .create(&root)518 .expect("the run root");519 let mut spec = inf3r_container::ContainerSpec::new(image(), "cli-exit");520 spec.command = vec!["sh".into(), "-c".into(), "sleep 30".into()];521 let mut child = inf3r_supervisor::Child::spawn_container_in(spec, &root)522 .expect("the supervisor starts a container");523 let name = child.container_name().expect("a container child");524 let deadline = std::time::Instant::now() + Duration::from_secs(10);525 while !container_running(&name) && std::time::Instant::now() < deadline {526 std::thread::sleep(Duration::from_millis(20));527 }528 assert!(container_running(&name), "the container did not start");529 let mut found = None;530 for _ in 0..100 {531 found = docker_cli_pid(&name);532 if found.is_some() {533 break;534 }535 std::thread::sleep(Duration::from_millis(20));536 }537 let pid = found.expect("the docker run CLI");538 let _ = Command::new("kill").args(["-9", &pid.to_string()]).status();539 for _ in 0..100 {540 if !child.alive() {541 break;542 }543 std::thread::sleep(Duration::from_millis(20));544 }545 let _ = child.stop(Duration::from_secs(2));546 let listed = docker()547 .args([548 "ps",549 "-a",550 "--filter",551 &format!("name={name}"),552 "--format",553 "{{.Names}}",554 ])555 .output()556 .expect("docker ps");557 assert!(558 !String::from_utf8_lossy(&listed.stdout).contains(&name),559 "the container survived stop after its CLI exited: {name}"560 );561 let _ = docker()562 .args(["rm", "-f", &name])563 .stdout(Stdio::null())564 .stderr(Stdio::null())565 .status();566 let _ = fs::remove_dir_all(root);567 }