Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-sdk): a restarted microVM comes back, restart waits for the guest, and Apple's Containerization pulls private images (#6308)

ddupontf48a905ca688
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index e2962aa37a..3f7b4f8b32 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -38,7 +38,7 @@ use cua_vmm::{
VmmError,
auto::{self, DoctorReport},
container::{ContainerConfig, ContainerRuntime},
- containerization::ContainerizationRuntime,
+ containerization::{ContainerizationConfig, ContainerizationRuntime},
lume::LumeRuntime,
managed::{self, LinuxSource},
microvm::{MicroVmConfig, MicroVmRuntime},
@@ -621,7 +621,13 @@ impl VmmLocal {
resolver: Some(cua_image::RootfsLayerResolver::shared()),
..MicroVmConfig::default()
})),
- apple: Arc::new(ContainerizationRuntime::with_defaults()),
+ // Images come through the shared puller (the host's registry
+ // credentials, mirrors and layer cache), then load into
+ // Apple's store.
+ apple: Arc::new(ContainerizationRuntime::new(ContainerizationConfig {
+ resolver: Some(cua_image::RootfsLayerResolver::shared()),
+ ..ContainerizationConfig::default()
+ })),
pool: std::sync::OnceLock::new(),
named_state: Default::default(),
resolved: Default::default(),
@@ -2891,7 +2897,12 @@ pub(crate) fn headless_command_line() -> Vec<String> {
"/bin/sh".into(),
"-c".into(),
concat!(
- "if [ -z \"$CUA_ENV_TOKEN\" ]; then ",
+ // A guest that awaits its token file (a microVM's init writes it,
+ // and rewrites it at every boot) must not also be handed the
+ // token in the environment: cua-spacesd refuses both ("--await-token-file
+ // takes the token only from --token-file"), so a restarted microVM,
+ // whose token file already held the token, never came back.
+ "if [ \"$CUA_ENV_AWAIT_TOKEN_FILE\" != 1 ] && [ -z \"$CUA_ENV_TOKEN\" ]; then ",
"for f in /run/cua/env-token /etc/cua/env-token; do ",
"if [ -r \"$f\" ]; then CUA_ENV_TOKEN=$(tr -d '\\r\\n' < \"$f\"); export CUA_ENV_TOKEN; break; fi; ",
"done; fi; ",
@@ -3176,6 +3187,51 @@ mod tests {
);
}
+ /// A guest that awaits its token file (every microVM whose token is
+ /// delivered later) is never also handed the token through the
+ /// environment: cua-spacesd refuses both, and a restarted microVM, whose
+ /// token file already held the token, never came back.
+ #[cfg(unix)]
+ #[test]
+ fn a_headless_guest_that_awaits_its_token_file_is_not_given_the_token_too() {
+ use std::os::unix::fs::PermissionsExt;
+ let cmd = headless_command_line();
+ let script = &cmd[2];
+ assert!(
+ script.contains("\"$CUA_ENV_AWAIT_TOKEN_FILE\" != 1"),
+ "the token files are read only when the guest does not await its own: {script}"
+ );
+ let dir = std::env::temp_dir().join(format!("cua-headless-cmd-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let stub = dir.join("spacesd");
+ std::fs::write(
+ &stub,
+ "#!/bin/sh\necho \"token=[$CUA_ENV_TOKEN] await=[$CUA_ENV_AWAIT_TOKEN_FILE]\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let run = |env: &[(&str, &str)]| {
+ let mut c = std::process::Command::new(&cmd[0]);
+ c.args(&cmd[1..])
+ .env_remove("CUA_ENV_TOKEN")
+ .env_remove("CUA_ENV_AWAIT_TOKEN_FILE")
+ .env("CUA_SPACESD_BIN", &stub);
+ for (k, v) in env {
+ c.env(k, v);
+ }
+ String::from_utf8_lossy(&c.output().unwrap().stdout)
+ .trim()
+ .to_string()
+ };
+ assert_eq!(
+ run(&[("CUA_ENV_AWAIT_TOKEN_FILE", "1")]),
+ "token=[] await=[1]"
+ );
+ // A token the runtime put in the environment still passes through.
+ assert_eq!(run(&[("CUA_ENV_TOKEN", "abc")]), "token=[abc] await=[]");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn only_backends_whose_claim_delivers_the_token_skip_the_pool_secret() {
assert!(claim_delivers_token(BackendKind::Firecracker));
diff --git a/libs/cua/crates/cua-image/src/rootfs.rs b/libs/cua/crates/cua-image/src/rootfs.rs
index 887e46a73f..8e57da22a8 100644
--- a/libs/cua/crates/cua-image/src/rootfs.rs
+++ b/libs/cua/crates/cua-image/src/rootfs.rs
@@ -267,6 +267,25 @@ pub async fn pull_layers(
Some(d) => run_config(&client.blob_bytes(&pinned, d).await?)?,
None => cua_vmm::OciRunConfig::default(),
};
+ let files = fetch_layers(client, cache, reference, &pinned, &manifest).await?;
+ cache.record_ref(reference, &digest)?;
+ Ok(cua_vmm::RootfsLayers {
+ digest,
+ layers: files,
+ config,
+ })
+}
+
+/// Downloads the layer blobs of `manifest` that the cache lacks (checking
+/// the disk first, reporting progress) and returns their files, bottom
+/// first.
+async fn fetch_layers(
+ client: &RegistryClient,
+ cache: &ImageCache,
+ reference: &str,
+ pinned: &str,
+ manifest: &crate::manifest::ImageManifest,
+) -> Result<Vec<PathBuf>> {
let missing: u64 = manifest
.layers
.iter()
@@ -295,17 +314,125 @@ pub async fn pull_layers(
.fraction(done as f64 / total as f64)
.detail(reference),
);
- client.blob_to_file(&pinned, layer, &blob).await?;
+ client.blob_to_file(pinned, layer, &blob).await?;
}
done += layer.size;
files.push(blob);
}
+ Ok(files)
+}
+
+/// `reference` as a runtime's image store names it: registry, repository
+/// and tag (or digest), the registry spelled out (`alpine` is
+/// `docker.io/library/alpine:latest`).
+pub fn image_name(reference: &str) -> Result<String> {
+ let r = crate::registry::parse_ref(reference)?;
+ Ok(r.whole())
+}
+
+/// One regular file of an archive.
+fn add_bytes<W: Write>(b: &mut tar::Builder<W>, name: &str, bytes: &[u8]) -> Result<()> {
+ let mut h = tar::Header::new_gnu();
+ h.set_size(bytes.len() as u64);
+ h.set_mode(0o644);
+ h.set_entry_type(tar::EntryType::Regular);
+ b.append_data(&mut h, name, bytes)?;
+ Ok(())
+}
+
+/// Pulls `reference` (the layers into the blob cache, as [`pull_layers`])
+/// and writes it to `out` as an OCI image layout archive: `oci-layout`,
+/// `index.json` naming the platform manifest as [`image_name`] says, and
+/// every blob (manifest, config, layers) byte for byte as the registry
+/// served it, so each digest holds. Returns the platform manifest's digest.
+/// `out` is written whole or not at all.
+pub async fn pull_oci_archive(
+ client: &RegistryClient,
+ cache: &ImageCache,
+ reference: &str,
+ arch: &str,
+ out: &Path,
+) -> Result<String> {
+ let (pinned, manifest, digest) = client.resolve_platform(reference, arch).await?;
+ let (raw_manifest, raw_digest) = client.manifest_bytes(&pinned).await?;
+ if raw_digest != digest {
+ return Err(ImageError::Registry(format!(
+ "{reference}: the registry served manifest {raw_digest}, not {digest}"
+ )));
+ }
+ let config_desc = manifest
+ .config
+ .clone()
+ .ok_or_else(|| ImageError::Registry(format!("{reference}: the manifest has no config")))?;
+ let config = client.blob_bytes(&pinned, &config_desc).await?;
+ let layers = fetch_layers(client, cache, reference, &pinned, &manifest).await?;
cache.record_ref(reference, &digest)?;
- Ok(cua_vmm::RootfsLayers {
- digest,
- layers: files,
- config,
- })
+ let name = image_name(reference)?;
+ let tag = crate::registry::parse_ref(reference)?
+ .tag()
+ .map(str::to_string);
+ let media_type = if manifest.media_type.is_empty() {
+ crate::media_types::OCI_MANIFEST.to_string()
+ } else {
+ manifest.media_type.clone()
+ };
+ let mut annotations = serde_json::Map::new();
+ annotations.insert("io.containerd.image.name".into(), name.into());
+ if let Some(t) = tag {
+ annotations.insert("org.opencontainers.image.ref.name".into(), t.into());
+ }
+ let index = serde_json::json!({
+ "schemaVersion": 2,
+ "manifests": [{
+ "mediaType": media_type,
+ "digest": digest,
+ "size": raw_manifest.len(),
+ "annotations": annotations,
+ }]
+ });
+ let total: u64 = manifest.layers.iter().map(|l| l.size).sum();
+ if let Some(dir) = out.parent() {
+ std::fs::create_dir_all(dir)?;
+ cua_vmm::disk::ensure_space(dir, total, &format!("pack {reference}"))
+ .map_err(cua_vmm::VmmError::from)?;
+ }
+ let partial = out.with_extension("partial");
+ let blob_name = |d: &str| -> Result<String> {
+ Ok(format!(
+ "blobs/sha256/{}",
+ cache
+ .blob_path(d)?
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or_default()
+ ))
+ };
+ let result = (|| -> Result<()> {
+ let mut b = tar::Builder::new(std::io::BufWriter::with_capacity(
+ 1 << 20,
+ std::fs::File::create(&partial)?,
+ ));
+ add_bytes(&mut b, "oci-layout", br#"{"imageLayoutVersion":"1.0.0"}"#)?;
+ add_bytes(&mut b, "index.json", &serde_json::to_vec(&index)?)?;
+ add_bytes(&mut b, &blob_name(&digest)?, &raw_manifest)?;
+ add_bytes(&mut b, &blob_name(&config_desc.digest)?, &config)?;
+ for (desc, file) in manifest.layers.iter().zip(&layers) {
+ let mut f = std::fs::File::open(file)?;
+ let mut h = tar::Header::new_gnu();
+ h.set_size(f.metadata()?.len());
+ h.set_mode(0o644);
+ h.set_entry_type(tar::EntryType::Regular);
+ b.append_data(&mut h, blob_name(&desc.digest)?, &mut f)?;
+ }
+ b.into_inner()?.into_inner().map_err(|e| e.into_error())?;
+ std::fs::rename(&partial, out)?;
+ Ok(())
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&partial);
+ }
+ result?;
+ Ok(digest)
}
/// [`cua_vmm::RootfsResolver`] over the image cache (microVM rootfs
@@ -340,6 +467,24 @@ impl cua_vmm::RootfsResolver for RootfsLayerResolver {
};
Ok(pull_layers(client, &self.cache, reference, arch.oci()).await?)
}
+
+ async fn pull_oci_archive(
+ &self,
+ reference: &str,
+ arch: cua_vmm::Arch,
+ creds: Option<&cua_vmm::RegistryCredentials>,
+ out: &Path,
+ ) -> cua_vmm::Result<String> {
+ let scoped;
+ let client = match creds {
+ Some(c) => {
+ scoped = RegistryClient::with_credentials(c.clone());
+ &scoped
+ }
+ None => &self.client,
+ };
+ Ok(pull_oci_archive(client, &self.cache, reference, arch.oci(), out).await?)
+ }
}
#[cfg(test)]
diff --git a/libs/cua/crates/cua-image/tests/oci_archive.rs b/libs/cua/crates/cua-image/tests/oci_archive.rs
new file mode 100644
index 0000000000..294175f5ac
--- /dev/null
+++ b/libs/cua/crates/cua-image/tests/oci_archive.rs
@@ -0,0 +1,204 @@
+//! `pull_oci_archive`: an image pulled with the caller's registry
+//! credential comes out as an OCI image layout archive that keeps every
+//! blob byte for byte (so a runtime with its own image store, Apple's
+//! `container`, can load it), against a loopback registry that wants a
+//! login. Its own test binary, since it sets env vars.
+
+use std::collections::BTreeMap;
+use std::io::Read;
+use std::sync::Arc;
+
+use base64::Engine;
+use cua_image::digest::sha256_bytes;
+use cua_image::{ImageCache, RegistryClient, RegistryCredentials, RootfsLayerResolver};
+use cua_vmm::{Arch, RootfsResolver};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+type Docs = Arc<BTreeMap<String, (String, Vec<u8>)>>;
+
+/// Serves `docs` (path -> content type and bytes); `/v2/` and everything
+/// else answers 401 (Basic) unless the request carries `auth`.
+async fn serve(listener: TcpListener, docs: Docs, auth: String) {
+ loop {
+ let Ok((mut s, _)) = listener.accept().await else {
+ return;
+ };
+ let (docs, auth) = (docs.clone(), auth.clone());
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 16 << 10];
+ let mut n = 0;
+ while n < buf.len() {
+ let Ok(k) = s.read(&mut buf[n..]).await else {
+ return;
+ };
+ if k == 0 {
+ return;
+ }
+ n += k;
+ if buf[..n].windows(4).any(|w| w == b"\r\n\r\n") {
+ break;
+ }
+ }
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let path = req.split_whitespace().nth(1).unwrap_or("").to_string();
+ let authed = req
+ .lines()
+ .any(|l| l.to_ascii_lowercase().starts_with("authorization:") && l.contains(&auth));
+ if !authed {
+ let _ = s
+ .write_all(
+ b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"fixture\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )
+ .await;
+ return;
+ }
+ if path == "/v2/" {
+ let _ = s
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
+ )
+ .await;
+ return;
+ }
+ match docs.get(&path) {
+ Some((ct, body)) => {
+ let digest = sha256_bytes(body);
+ let head = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: {ct}\r\nDocker-Content-Digest: {digest}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = s.write_all(head.as_bytes()).await;
+ let _ = s.write_all(body).await;
+ }
+ None => {
+ let _ = s
+ .write_all(
+ b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )
+ .await;
+ }
+ }
+ });
+ }
+}
+
+#[tokio::test]
+async fn a_private_image_is_packed_unchanged_with_the_callers_credential() {
+ let layer1 = b"layer one bytes (stand-in for a gzip tar)".to_vec();
+ let layer2 = vec![7u8; 4096];
+ let config = serde_json::to_vec(&serde_json::json!({
+ "architecture": "arm64", "os": "linux",
+ "config": {"Cmd": ["/bin/true"], "User": "cua"},
+ "rootfs": {"type": "layers", "diff_ids": []}
+ }))
+ .unwrap();
+ let layer = |b: &[u8]| {
+ serde_json::json!({
+ "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
+ "digest": sha256_bytes(b), "size": b.len()
+ })
+ };
+ let manifest = serde_json::to_vec(&serde_json::json!({
+ "schemaVersion": 2,
+ "mediaType": "application/vnd.oci.image.manifest.v1+json",
+ "config": {
+ "mediaType": "application/vnd.oci.image.config.v1+json",
+ "digest": sha256_bytes(&config), "size": config.len()
+ },
+ "layers": [layer(&layer1), layer(&layer2)]
+ }))
+ .unwrap();
+ let mdigest = sha256_bytes(&manifest);
+ let mt = "application/vnd.oci.image.manifest.v1+json".to_string();
+ let mut docs: BTreeMap<String, (String, Vec<u8>)> = BTreeMap::new();
+ docs.insert(
+ "/v2/test/img/manifests/v1".into(),
+ (mt.clone(), manifest.clone()),
+ );
+ docs.insert(
+ format!("/v2/test/img/manifests/{mdigest}"),
+ (mt, manifest.clone()),
+ );
+ for blob in [&config, &layer1, &layer2] {
+ docs.insert(
+ format!("/v2/test/img/blobs/{}", sha256_bytes(blob)),
+ ("application/octet-stream".into(), blob.clone()),
+ );
+ }
+ let auth = base64::engine::general_purpose::STANDARD.encode("reader:s3cret");
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let host = format!("127.0.0.1:{}", listener.local_addr().unwrap().port());
+ tokio::spawn(serve(listener, Arc::new(docs), auth));
+ let empty = tempfile::tempdir().unwrap().keep();
+ unsafe {
+ std::env::set_var("DOCKER_CONFIG", &empty);
+ std::env::set_var("CUA_REGISTRY_CRED_HELPERS", "0");
+ std::env::remove_var("CUA_REGISTRY_USERNAME");
+ std::env::remove_var("CUA_REGISTRY_PASSWORD");
+ std::env::remove_var("GITHUB_TOKEN");
+ std::env::set_var("CUA_INSECURE_REGISTRIES", &host);
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let resolver = RootfsLayerResolver {
+ client: RegistryClient::default(),
+ cache: ImageCache::new(tmp.path().join("images")),
+ };
+ let reference = format!("{host}/test/img:v1");
+ let out = tmp.path().join("run").join("image.tar");
+
+ // No credential: refused, and nothing is left behind.
+ let e = resolver
+ .pull_oci_archive(&reference, Arch::Aarch64, None, &out)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(
+ e.to_lowercase().contains("not authorized")
+ || e.to_lowercase().contains("unauthorized")
+ || e.contains("sign-in")
+ || e.contains("private"),
+ "{e}"
+ );
+ assert!(!out.exists());
+ assert!(!out.with_extension("partial").exists());
+
+ // With the credential: the archive holds the blobs unchanged.
+ let creds = RegistryCredentials::new("reader", "s3cret").for_registry(&host);
+ let digest = resolver
+ .pull_oci_archive(&reference, Arch::Aarch64, Some(&creds), &out)
+ .await
+ .unwrap();
+ assert_eq!(digest, mdigest);
+ assert!(!out.with_extension("partial").exists());
+
+ let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
+ let mut ar = tar::Archive::new(std::fs::File::open(&out).unwrap());
+ for entry in ar.entries().unwrap() {
+ let mut e = entry.unwrap();
+ let name = e.path().unwrap().to_string_lossy().to_string();
+ let mut b = Vec::new();
+ e.read_to_end(&mut b).unwrap();
+ files.insert(name, b);
+ }
+ assert_eq!(files["oci-layout"], br#"{"imageLayoutVersion":"1.0.0"}"#);
+ let blob = |b: &[u8]| format!("blobs/sha256/{}", &sha256_bytes(b)[7..]);
+ assert_eq!(files[&blob(&manifest)], manifest, "the manifest as served");
+ assert_eq!(files[&blob(&config)], config);
+ assert_eq!(files[&blob(&layer1)], layer1);
+ assert_eq!(files[&blob(&layer2)], layer2);
+ let index: serde_json::Value = serde_json::from_slice(&files["index.json"]).unwrap();
+ let m = &index["manifests"][0];
+ assert_eq!(m["digest"], mdigest);
+ assert_eq!(m["size"], manifest.len());
+ assert_eq!(m["mediaType"], "application/vnd.oci.image.manifest.v1+json");
+ assert_eq!(
+ m["annotations"]["io.containerd.image.name"],
+ format!("{host}/test/img:v1")
+ );
+ assert_eq!(m["annotations"]["org.opencontainers.image.ref.name"], "v1");
+
+ // The credential is nowhere in the archive.
+ let all: Vec<u8> = files.values().flatten().copied().collect();
+ assert!(!String::from_utf8_lossy(&all).contains("s3cret"));
+}
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
index 8de0ee54b6..4097865d60 100644
--- a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
@@ -1988,7 +1988,10 @@ impl Sandboxes {
rt.stop(name).await?;
let inst = rt.resume(name).await?;
self.record_endpoints(name, &inst)?;
- self.inner.state.set_status(name, "running")
+ self.inner.state.set_status(name, "running")?;
+ // Restarted means answering, as a resume and a resize are
+ // waited for: a VM's resume returns while its guest boots.
+ self.wait_recorded_probes(name).await
}
(kind, _) => Err(Error::Unsupported {
provider: kind,
@@ -2016,18 +2019,7 @@ impl Sandboxes {
self.inner.state.save(&SandboxState::Local(l))?;
}
self.inner.state.set_status(name, "running")?;
- let probes = self
- .inner
- .state
- .load_raw(name)
- .and_then(|m| m.get("ready_probes").cloned())
- .map(probes_from_json)
- .unwrap_or_default();
- if !probes.is_empty() {
- let sb = self.connect(name).await?;
- sb.wait_ready(&probes, RESUME_READY_TIMEOUT).await?;
- }
- Ok(())
+ self.wait_recorded_probes(name).await
}
(kind, s) => Err(Error::Unsupported {
provider: kind,
@@ -2036,6 +2028,23 @@ impl Sandboxes {
}
}
+ /// Waits for the ready probes recorded with sandbox `name` (none: it
+ /// answers when its runtime says so).
+ async fn wait_recorded_probes(&self, name: &str) -> Result<()> {
+ let probes = self
+ .inner
+ .state
+ .load_raw(name)
+ .and_then(|m| m.get("ready_probes").cloned())
+ .map(probes_from_json)
+ .unwrap_or_default();
+ if !probes.is_empty() {
+ let sb = self.connect(name).await?;
+ sb.wait_ready(&probes, RESUME_READY_TIMEOUT).await?;
+ }
+ Ok(())
+ }
+
/// How the sandbox `name` turns off and on again (`None`: it cannot,
/// or there is no such sandbox): a local instance as its runtime says
/// ([`LocalRuntime::power_control`]), a contrib one as its provider
diff --git a/libs/cua/crates/cua-sandbox-core/tests/providers.rs b/libs/cua/crates/cua-sandbox-core/tests/providers.rs
index 64c962bfb2..164ca7aac9 100644
--- a/libs/cua/crates/cua-sandbox-core/tests/providers.rs
+++ b/libs/cua/crates/cua-sandbox-core/tests/providers.rs
@@ -198,6 +198,12 @@ impl FakeRuntime {
async fn http_responder(status: u16) -> u16 {
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = l.local_addr().unwrap().port();
+ serve_http(l, status);
+ port
+}
+
+/// Answers every request on `l` with `status`.
+fn serve_http(l: TcpListener, status: u16) {
tokio::spawn(async move {
while let Ok((mut s, _)) = l.accept().await {
tokio::spawn(async move {
@@ -216,7 +222,6 @@ async fn http_responder(status: u16) -> u16 {
});
}
});
- port
}
async fn echo_server() -> u16 {
@@ -333,7 +338,7 @@ async fn local_lifecycle_state_and_readiness() {
sbx.resume("dev-box").await.unwrap();
// A runtime that publishes on new host ports when it boots again (a
// microVM does): the state follows, so connections reach the new ones.
- let moved = web.wrapping_add(1);
+ let moved = http_responder(204).await;
rt.map(80, moved);
sbx.restart("dev-box").await.unwrap();
match sbx.state().load("dev-box").unwrap() {
@@ -355,6 +360,45 @@ async fn local_lifecycle_state_and_readiness() {
);
}
+/// A restarted sandbox is waited for as a created one is: `restart` returns
+/// once the ready probes recorded at create pass (a VM's resume returns
+/// while its guest is still booting), on every runtime alike.
+#[tokio::test]
+async fn restart_waits_for_the_ready_probes() {
+ let dir = tempfile::tempdir().unwrap();
+ let rt = Arc::new(FakeRuntime::default());
+ let web = http_responder(204).await;
+ rt.map(80, web);
+ rt.map(3211, closed_port());
+ let sbx = Sandboxes::builder()
+ .local(rt.clone())
+ .state_dir(dir.path())
+ .build();
+ sbx.create(
+ CreateOptions::new(ProviderKind::Local, "img")
+ .name("slow-boot")
+ .service("web", 80)
+ .wait_for(Probe::Tcp(80)),
+ )
+ .await
+ .unwrap();
+ // It boots again on a port that starts to answer only after a while.
+ let late = closed_port();
+ rt.map(80, late);
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(900)).await;
+ let l = TcpListener::bind(("127.0.0.1", late)).await.unwrap();
+ serve_http(l, 204);
+ });
+ let t = std::time::Instant::now();
+ sbx.restart("slow-boot").await.unwrap();
+ assert!(
+ t.elapsed() >= Duration::from_millis(800),
+ "restart returned after {:?}, before the guest answered",
+ t.elapsed()
+ );
+}
+
#[tokio::test]
async fn readiness_probe_timeout_cleans_up_ephemeral() {
let dir = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-vmm/src/containerization/cli.rs b/libs/cua/crates/cua-vmm/src/containerization/cli.rs
index c52d402ea9..945162fd4f 100644
--- a/libs/cua/crates/cua-vmm/src/containerization/cli.rs
+++ b/libs/cua/crates/cua-vmm/src/containerization/cli.rs
@@ -40,6 +40,10 @@ pub fn shm_mib(memory_mb: u64) -> u64 {
/// loopback forwarder runs in a launchd helper that macOS's Local Network
/// privacy keeps from reaching the guest).
///
+/// `dns`: the nameservers the guest uses ([`guest_dns`]); the guest never
+/// gets vmnet's own resolver, which answers with the truncated bit set and
+/// serves no TCP.
+///
/// `inject_dir`: the host directory holding the injected cua-spacesd
/// ([`crate::inject`]), bound read-only at [`crate::inject::GUEST_DIR`]; the
/// supervisor it runs starts as root.
@@ -49,6 +53,7 @@ pub fn run_args(
env_file: Option<&str>,
labels: &BTreeMap<String, String>,
inject_dir: Option<&str>,
+ dns: &[String],
) -> Vec<String> {
let mut a: Vec<String> = vec![
"run".into(),
@@ -72,6 +77,11 @@ pub fn run_args(
a.push("--arch".into());
a.push(arch.oci().into());
}
+ // The guest's resolvers: see [`guest_dns`].
+ for ns in dns {
+ a.push("--dns".into());
+ a.push(ns.clone());
+ }
for (k, v) in labels {
a.push("--label".into());
a.push(format!("{k}={v}"));
@@ -361,6 +371,112 @@ pub fn parse_containers(stdout: &str) -> Result<Vec<ContainerInfo>, serde_json::
})
}
+/// A short stable name for `s` (a file name that never collides across
+/// images).
+pub fn short_hash(s: &str) -> String {
+ use sha2::{Digest, Sha256};
+ let d = Sha256::digest(s.as_bytes());
+ d[..6].iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// Public resolvers a guest falls back on (after the host's own).
+pub const FALLBACK_DNS: [&str; 2] = ["1.1.1.1", "8.8.8.8"];
+
+/// The nameservers for a guest, in order: `$CUA_GUEST_DNS` (a comma list)
+/// when set, else the host's own IPv4 resolvers from `resolv_conf` (its
+/// `/etc/resolv.conf`; never a loopback, link-local or unspecified one, which
+/// only the host reaches), at most two, then [`FALLBACK_DNS`].
+///
+/// Why not the resolver `container` configures (the vmnet gateway,
+/// `192.168.64.1`): it answers every AAAA lookup with the truncated bit
+/// set although the answer is whole, so glibc retries over TCP, the
+/// gateway serves none, and `getaddrinfo` fails with "Temporary failure in
+/// name resolution" for every name that is looked up for both families
+/// (curl, node, git, pip). Programs that ask for IPv4 alone worked, which
+/// is why the guest could `getent hosts` a name and still not download.
+pub fn guest_dns(env: Option<&str>, resolv_conf: &str) -> Vec<String> {
+ use std::net::Ipv4Addr;
+ fn valid(ip: &Ipv4Addr) -> bool {
+ !(ip.is_loopback() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast())
+ }
+ fn push(out: &mut Vec<String>, ip: Ipv4Addr) {
+ let s = ip.to_string();
+ if !out.contains(&s) {
+ out.push(s);
+ }
+ }
+ let mut out: Vec<String> = Vec::new();
+ if let Some(list) = env.map(str::trim).filter(|l| !l.is_empty()) {
+ for item in list.split(',') {
+ if let Ok(ip) = item.trim().parse::<Ipv4Addr>()
+ && valid(&ip)
+ {
+ push(&mut out, ip);
+ }
+ }
+ if !out.is_empty() {
+ return out;
+ }
+ }
+ let mut host = 0;
+ for line in resolv_conf.lines() {
+ let mut w = line.split_whitespace();
+ if w.next() != Some("nameserver") {
+ continue;
+ }
+ if let Some(Ok(ip)) = w.next().map(str::parse::<Ipv4Addr>)
+ && valid(&ip)
+ && host < 2
+ {
+ push(&mut out, ip);
+ host += 1;
+ }
+ }
+ for f in FALLBACK_DNS {
+ if let Ok(ip) = f.parse() {
+ push(&mut out, ip);
+ }
+ }
+ out
+}
+
+/// Whether `container image inspect --format json` output (one image or a
+/// list) holds a variant whose manifest digest is `digest`: the image the
+/// registry serves now is already in the store.
+pub fn image_has_variant(stdout: &str, digest: &str) -> bool {
+ let Ok(v) = serde_json::from_str::<Value>(stdout.trim()) else {
+ return false;
+ };
+ let images: Vec<&Value> = match &v {
+ Value::Array(a) => a.iter().collect(),
+ other => vec![other],
+ };
+ images.iter().any(|i| {
+ i.get("variants")
+ .and_then(Value::as_array)
+ .is_some_and(|vs| {
+ vs.iter()
+ .any(|x| x.get("digest").and_then(Value::as_str) == Some(digest))
+ })
+ })
+}
+
+/// Whether a failed pull's stderr says the registry wanted a sign-in
+/// (Apple's puller refuses a private package's anonymous token exchange
+/// with "refusing insecure credential exchange").
+pub fn auth_refused(stderr: &str) -> bool {
+ let s = stderr.to_ascii_lowercase();
+ [
+ "credential exchange",
+ "unauthorized",
+ "denied",
+ "authentication required",
+ "authentication challenge",
+ ]
+ .iter()
+ .any(|k| s.contains(k))
+}
+
/// Whether a failed command's stderr says the container does not exist.
pub fn not_found(stderr: &str) -> bool {
let s = stderr.to_ascii_lowercase();
@@ -394,6 +510,7 @@ mod tests {
Some("/tmp/env"),
&labels,
None,
+ &["192.168.1.1".to_string(), "1.1.1.1".to_string()],
);
let s = a.join(" ");
assert!(
@@ -403,6 +520,7 @@ mod tests {
assert!(s.contains("--shm-size 2048M"), "{s}");
assert!(s.contains("--label ai.cua.managed=true"), "{s}");
assert!(s.contains("--env-file /tmp/env"), "{s}");
+ assert!(s.contains("--dns 192.168.1.1 --dns 1.1.1.1"), "{s}");
assert!(!s.contains("--publish"), "{s}");
assert!(
s.ends_with("--entrypoint /bin/sh ghcr.io/trycua/linux@sha256:ab -c sleep 1"),
@@ -410,7 +528,7 @@ mod tests {
);
// No command: the image's own ENTRYPOINT/CMD.
spec.command = Some(vec![]);
- let a = run_args(&spec, "img", None, &BTreeMap::new(), None);
+ let a = run_args(&spec, "img", None, &BTreeMap::new(), None, &[]);
assert_eq!(a.last().map(String::as_str), Some("img"));
assert!(!a.contains(&"--entrypoint".to_string()));
assert!(!a.contains(&"--env-file".to_string()));
@@ -426,7 +544,14 @@ mod tests {
"--on-exit".into(),
"serve".into(),
]);
- let a = run_args(&spec, "alpine:3.20", None, &BTreeMap::new(), Some("/h/sd"));
+ let a = run_args(
+ &spec,
+ "alpine:3.20",
+ None,
+ &BTreeMap::new(),
+ Some("/h/sd"),
+ &[],
+ );
let s = a.join(" ");
assert!(s.contains("--user 0"), "{s}");
assert!(
@@ -439,6 +564,54 @@ mod tests {
);
}
+ #[test]
+ fn a_guest_resolves_through_the_hosts_resolvers_not_vmnets() {
+ let conf = "# macOS\nsearch lan\nnameserver 192.168.1.1\nnameserver fe80::1%en0\n\
+ nameserver 127.0.0.1\nnameserver 10.0.0.2\nnameserver 10.0.0.3\n";
+ // The host's first two IPv4 resolvers, then the public fallback; a
+ // loopback or link-local one is never named (the guest cannot
+ // reach it).
+ assert_eq!(
+ guest_dns(None, conf),
+ ["192.168.1.1", "10.0.0.2", "1.1.1.1", "8.8.8.8"]
+ );
+ // A host with no usable resolver still resolves.
+ assert_eq!(guest_dns(None, "nameserver 127.0.0.53\n"), FALLBACK_DNS);
+ assert_eq!(guest_dns(None, ""), FALLBACK_DNS);
+ // The override wins and is not extended; junk in it is dropped.
+ assert_eq!(
+ guest_dns(Some("9.9.9.9, nope, 127.0.0.1,149.112.112.112"), conf),
+ ["9.9.9.9", "149.112.112.112"]
+ );
+ assert_eq!(guest_dns(Some("nope"), ""), FALLBACK_DNS);
+ assert_eq!(
+ guest_dns(Some("1.1.1.1"), "nameserver 1.1.1.1\n"),
+ ["1.1.1.1"]
+ );
+ }
+
+ #[test]
+ fn a_loaded_image_is_found_by_its_manifest_digest() {
+ let out = r#"[{"id":"i","variants":[{"digest":"sha256:aa"},{"digest":"sha256:bb"}]}]"#;
+ assert!(image_has_variant(out, "sha256:bb"));
+ assert!(image_has_variant(
+ r#"{"variants":[{"digest":"sha256:cc"}]}"#,
+ "sha256:cc"
+ ));
+ assert!(!image_has_variant(out, "sha256:cc"));
+ assert!(!image_has_variant("[]", "sha256:aa"));
+ assert!(!image_has_variant("not json", "sha256:aa"));
+ }
+
+ #[test]
+ fn a_private_registrys_refusal_is_recognized() {
+ assert!(auth_refused(
+ "Error: refusing insecure credential exchange: authorization server https://ghcr.io/token issued its own authentication challenge"
+ ));
+ assert!(auth_refused("unauthorized: authentication required"));
+ assert!(!auth_refused("no space left on device"));
+ }
+
#[test]
fn the_run_config_comes_from_the_variant_of_the_architecture() {
let out = r#"[{"id":"abc","variants":[
diff --git a/libs/cua/crates/cua-vmm/src/containerization/mod.rs b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
index bd7b9de68d..298f99f817 100644
--- a/libs/cua/crates/cua-vmm/src/containerization/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/containerization/mod.rs
@@ -13,6 +13,39 @@
//! install of `container` runs them the backend refuses to start rather
//! than putting Spaces into, or stopping, a user's own setup.
//!
+//! **Images** are pulled the way every runtime pulls them: through the
+//! shared puller ([`ContainerizationConfig::resolver`], cua-image), which
+//! holds the host's registry credentials (the daemon's
+//! `CUA_REGISTRY_USERNAME` and `CUA_REGISTRY_PASSWORD`, `GITHUB_TOKEN` for
+//! ghcr.io, `docker login`, a Space's own `registry_auth`), mirrors and the
+//! layer cache the other runtimes share. The layers are packed unchanged
+//! into an OCI archive and handed to `container image load`, unless the
+//! store already holds the variant the registry serves. `container image
+//! pull` cannot do this: it can only use a login in the user's keychain
+//! (which cua never writes to), it refuses a private package's anonymous
+//! token exchange, and it pulled the 0.5 GB slim image in 178 s where the
+//! shared puller needed about 125 s on the same link (5.9 MB/s). Without a
+//! resolver `container` pulls by itself.
+//!
+//! **First start.** Apple's package (about 20 s) and, on the services' first
+//! start, its guest kernel (about 140 s) download before an image could
+//! begin, so the layers come down meanwhile (a prefetch through the same
+//! puller, joined before the container is made): a cold start of the slim
+//! image took 245 s instead of 253 to 307 s on a link that is the limit,
+//! and every later start is under 3 s.
+//!
+//! **Guest DNS.** Guests get the host's own resolvers (then public ones)
+//! with `--dns` ([`cli::guest_dns`]). The resolver `container` configures,
+//! the vmnet gateway, answers every AAAA query with the truncated bit set
+//! and serves no TCP, so `getaddrinfo` failed for every program that asks
+//! for both address families (curl, node, git, pip: a guest could not
+//! download its coding app) while `getent hosts` worked.
+//!
+//! **Network policy.** None can be enforced: the guests sit on vmnet,
+//! which only pf can filter and pf needs root, and Apple's runtime helper
+//! attaches no other network device. A Space with an egress policy or no
+//! network is refused here.
+//!
//! The environment (the Spaces token among it) goes in through an env file,
//! never the command line; the host reaches the guest's ports at its own
//! address on the vmnet network (as for a Lume VM: `container`'s loopback
@@ -77,14 +110,14 @@ use tokio::sync::Mutex;
use crate::error::{Result, VmmError};
use crate::exec::{ExecChunk, ExecOutput, ExecRequest, GuestExec};
use crate::host;
-use crate::runtime::Runtime;
+use crate::runtime::{RootfsResolver, Runtime};
use crate::types::*;
pub use cli::{ContainerInfo, Services};
pub use install::ContainerizationReport;
/// Configuration for [`ContainerizationRuntime`].
-#[derive(Clone, Debug)]
+#[derive(Clone)]
pub struct ContainerizationConfig {
/// State root (default `~/.cua/vmm/containerization`).
pub root: PathBuf,
@@ -96,6 +129,23 @@ pub struct ContainerizationConfig {
pub auto_install: bool,
/// How long `stop` lets the guest shut down before it is killed.
pub graceful_stop: Duration,
+ /// Pulls OCI images the way every other runtime does (implemented by
+ /// `cua-image`: the host's registry credentials, mirrors and the shared
+ /// layer cache), and hands them to `container` as an archive to load.
+ /// Without one `container` pulls by itself, anonymously.
+ pub resolver: Option<Arc<dyn RootfsResolver>>,
+}
+
+impl std::fmt::Debug for ContainerizationConfig {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ContainerizationConfig")
+ .field("root", &self.root)
+ .field("bin", &self.bin)
+ .field("auto_install", &self.auto_install)
+ .field("graceful_stop", &self.graceful_stop)
+ .field("resolver", &self.resolver.as_ref().map(|_| "set"))
+ .finish()
+ }
}
impl Default for ContainerizationConfig {
@@ -107,6 +157,7 @@ impl Default for ContainerizationConfig {
.map(PathBuf::from),
auto_install: true,
graceful_stop: Duration::from_secs(5),
+ resolver: None,
}
}
}
@@ -276,7 +327,12 @@ impl ContainerizationRuntime {
"run `cua runtime setup containerization` to install it",
));
}
+ let t = std::time::Instant::now();
install::install(&self.cfg.root).await?;
+ tracing::info!(
+ ms = t.elapsed().as_millis() as u64,
+ "Apple container downloaded and expanded"
+ );
}
}
let ours = |app_root: &str| cli::same_dir(app_root, &self.app_root().to_string_lossy());
@@ -298,7 +354,12 @@ impl ContainerizationRuntime {
"--timeout".into(),
"60".into(),
];
+ let t = std::time::Instant::now();
self.cli(&args, Duration::from_secs(600)).await?;
+ tracing::info!(
+ ms = t.elapsed().as_millis() as u64,
+ "Apple container services started (the first start downloads its guest kernel)"
+ );
// `system start` reports success when launchd refuses its
// service because another install holds the name: check.
match self.services().await? {
@@ -503,15 +564,7 @@ impl ContainerizationRuntime {
}
// The image's own command, user and working directory: pulled, then
// read back from the image store.
- let budget = spec.ready_timeout.max(Duration::from_secs(600));
- let mut pull: Vec<String> = ["image", "pull", "--progress", "none"]
- .map(String::from)
- .into();
- if let Some(arch) = spec.arch {
- pull.extend(["--arch".into(), arch.oci().into()]);
- }
- pull.push(image.into());
- self.cli(&pull, budget).await?;
+ self.ensure_image(spec, image).await?;
let out = self
.cli(&["image".into(), "inspect".into(), image.into()], QUICK)
.await?;
@@ -529,6 +582,132 @@ impl ContainerizationRuntime {
Ok((dir, wrapped))
}
+ /// Makes `image` present in `container`'s image store, pulled the way
+ /// every runtime pulls: through the resolver ([`ContainerizationConfig::resolver`]),
+ /// which holds the host's registry credentials, mirrors and the shared
+ /// layer cache, then loaded as an archive. `container pull` itself can
+ /// only use a login kept in the user's keychain (which cua never writes
+ /// to) and refuses a private package's anonymous token exchange, and it
+ /// pulled about half as fast as the shared puller on the same link.
+ /// Without a resolver (tests) or when it cannot serve the image,
+ /// `container` pulls it itself, anonymously.
+ async fn ensure_image(&self, spec: &StartSpec, image: &str) -> Result<()> {
+ let budget = spec.ready_timeout.max(Duration::from_secs(600));
+ let mut through_cua: Option<VmmError> = None;
+ if let Some(resolver) = &self.cfg.resolver {
+ let lock = self.lock_for(&format!("image:{image}"));
+ let _g = lock.lock().await;
+ match self
+ .load_image(resolver.as_ref(), spec, image, budget)
+ .await
+ {
+ Ok(()) => return Ok(()),
+ // `container` cannot use a credential it was handed, so
+ // another pull would only hide the reason.
+ Err(e) if spec.registry_auth.is_some() => return Err(e),
+ Err(e) => {
+ tracing::warn!(image, error = %e, "could not pull through cua; `container` pulls it");
+ through_cua = Some(e);
+ }
+ }
+ }
+ let mut pull: Vec<String> = ["image", "pull", "--progress", "none"]
+ .map(String::from)
+ .into();
+ if let Some(arch) = spec.arch {
+ pull.extend(["--arch".into(), arch.oci().into()]);
+ }
+ pull.push(image.into());
+ match self.cli(&pull, budget).await {
+ Ok(_) => Ok(()),
+ Err(VmmError::Command { stderr, .. }) if cli::auth_refused(&stderr) => {
+ Err(sign_in_hint(image, through_cua))
+ }
+ Err(e) => Err(e),
+ }
+ }
+
+ /// Pulls `image` through `resolver` and loads it into `container`'s
+ /// store, unless the variant the registry serves now is there already.
+ async fn load_image(
+ &self,
+ resolver: &dyn RootfsResolver,
+ spec: &StartSpec,
+ image: &str,
+ budget: Duration,
+ ) -> Result<()> {
+ let arch = spec.effective_arch();
+ let creds = spec.registry_auth.as_ref();
+ // A digest names one image for good: if the store has it, the
+ // registry need not be asked (three requests, 0.7 s on every start).
+ if image.contains("@sha256:") && self.image_present(image).await {
+ return Ok(());
+ }
+ // The layers go to the shared cache; the digest says which variant
+ // the registry serves now.
+ let t = std::time::Instant::now();
+ let layers = resolver.resolve_rootfs(image, arch, creds).await?;
+ let pulled = t.elapsed();
+ if self.image_has(image, &layers.digest).await {
+ return Ok(());
+ }
+ let dir = self.cfg.root.join("run");
+ std::fs::create_dir_all(&dir)?;
+ let archive = dir.join(format!("image-{}.tar", cli::short_hash(image)));
+ let t = std::time::Instant::now();
+ let loaded: Result<String> = async {
+ let digest = resolver
+ .pull_oci_archive(image, arch, creds, &archive)
+ .await?;
+ let args: Vec<String> = vec![
+ "image".into(),
+ "load".into(),
+ "--input".into(),
+ archive.display().to_string(),
+ ];
+ let packed = t.elapsed();
+ let t = std::time::Instant::now();
+ self.cli(&args, budget).await?;
+ tracing::info!(
+ image,
+ pull_ms = pulled.as_millis() as u64,
+ pack_ms = packed.as_millis() as u64,
+ load_ms = t.elapsed().as_millis() as u64,
+ "image pulled through cua and loaded into Apple's store"
+ );
+ Ok(digest)
+ }
+ .await;
+ let _ = std::fs::remove_file(&archive);
+ let digest = loaded?;
+ if !self.image_has(image, &digest).await {
+ return Err(VmmError::other(format!(
+ "`container` loaded {image} but does not list it"
+ )));
+ }
+ Ok(())
+ }
+
+ /// Whether the store holds `image` at all.
+ async fn image_present(&self, image: &str) -> bool {
+ let args = ["image".to_string(), "inspect".into(), image.into()];
+ self.cli(&args, QUICK).await.is_ok()
+ }
+
+ /// Whether the store holds `image` with a variant of manifest `digest`.
+ async fn image_has(&self, image: &str, digest: &str) -> bool {
+ let args = ["image".to_string(), "inspect".into(), image.into()];
+ self.cli(&args, QUICK)
+ .await
+ .is_ok_and(|out| cli::image_has_variant(&out, digest))
+ }
+
+ /// The nameservers for a guest ([`cli::guest_dns`]).
+ fn guest_dns(&self) -> Vec<String> {
+ let conf = std::fs::read_to_string("/etc/resolv.conf").unwrap_or_default();
+ cli::guest_dns(std::env::var("CUA_GUEST_DNS").ok().as_deref(), &conf)
+ }
+
/// Creates and starts the container for `spec`.
async fn create(&self, spec: &StartSpec, image: &str) -> Result<()> {
let injected;
@@ -538,7 +717,14 @@ impl ContainerizationRuntime {
injected = wrapped;
(&injected, Some(dir))
}
- None => (spec, None),
+ None => {
+ // `container run` would pull a missing image anonymously;
+ // the shared puller holds the credentials.
+ if self.cfg.resolver.is_some() {
+ self.ensure_image(spec, image).await?;
+ }
+ (spec, None)
+ }
};
let mut labels = BTreeMap::from([
(
@@ -577,6 +763,7 @@ impl ContainerizationRuntime {
env_file.as_deref().and_then(Path::to_str),
&labels,
inject_dir.as_deref().and_then(Path::to_str),
+ &self.guest_dns(),
);
let budget = spec.ready_timeout.max(Duration::from_secs(600));
let r = self.cli(&args, budget).await;
@@ -584,6 +771,12 @@ impl ContainerizationRuntime {
let _ = std::fs::remove_file(p);
}
if let Err(e) = r {
+ let e = match e {
+ VmmError::Command { stderr, .. } if cli::auth_refused(&stderr) => {
+ sign_in_hint(image, None)
+ }
+ other => other,
+ };
// A half-made container would hold the name.
let _ = self
.cli(
@@ -597,6 +790,20 @@ impl ContainerizationRuntime {
}
}
+/// What a person can do when `image` needs a registry sign-in: the reason
+/// the shared puller gave when it was asked first (the registry's own words),
+/// else how to give Cua the credential.
+fn sign_in_hint(image: &str, through_cua: Option<VmmError>) -> VmmError {
+ VmmError::other(match through_cua {
+ Some(e) => e.to_string(),
+ None => format!(
+ "{image} is private or needs a registry sign-in. Cua pulls with the credentials \
+ it holds (CUA_REGISTRY_USERNAME and CUA_REGISTRY_PASSWORD in the daemon's \
+ environment, `docker login`, or GITHUB_TOKEN for ghcr.io)"
+ ),
+ })
+}
+
fn other_install(app_root: &str) -> VmmError {
VmmError::other(format!(
"Apple's container services are running from another install of `container` \
@@ -636,19 +843,41 @@ impl Runtime for ContainerizationRuntime {
op: "a disk size (the image's filesystem grows as needed)",
});
}
- if spec.registry_auth.is_some() {
- return Err(VmmError::Unsupported {
- backend: "containerization",
- op: "registry credentials (microVM Spaces pull public images)",
- });
- }
if !cli::valid_name(&spec.name) {
return Err(VmmError::invalid(format!(
"{:?} is not a valid microVM name (letters, digits, '_', '.', '-', at most 63)",
spec.name
)));
}
+ // The first start downloads and starts Apple's container (about
+ // 20 s for its package, then about 140 s for the guest kernel its
+ // services fetch on their first start) before the image could
+ // begin: the image's layers come down meanwhile through the shared
+ // puller, which needs none of that. Joined before the container is
+ // made, so nothing downloads twice.
+ let prefetch = match (&spec.image, &self.cfg.resolver) {
+ (ImageSource::Oci { reference }, Some(resolver))
+ if !self.ready.load(Ordering::SeqCst) =>
+ {
+ let (resolver, reference) = (resolver.clone(), reference.clone());
+ let (arch, creds) = (spec.effective_arch(), spec.registry_auth.clone());
+ // One download of an image at a time (the same lock as
+ // [`Self::ensure_image`]): two starts of the same image must
+ // not write one blob file together.
+ let lock = self.lock_for(&format!("image:{reference}"));
+ Some(tokio::spawn(async move {
+ let _g = lock.lock().await;
+ let _ = resolver
+ .resolve_rootfs(&reference, arch, creds.as_ref())
+ .await;
+ }))
+ }
+ _ => None,
+ };
self.ensure_ready().await?;
+ if let Some(prefetch) = prefetch {
+ let _ = prefetch.await;
+ }
let lock = self.lock_for(&spec.name);
let _g = lock.lock().await;
match self.inspect(&spec.name).await {
diff --git a/libs/cua/crates/cua-vmm/src/runtime.rs b/libs/cua/crates/cua-vmm/src/runtime.rs
index 38484d4dab..32d7abc548 100644
--- a/libs/cua/crates/cua-vmm/src/runtime.rs
+++ b/libs/cua/crates/cua-vmm/src/runtime.rs
@@ -304,6 +304,31 @@ pub trait RootfsResolver: Send + Sync {
arch: Arch,
creds: Option<&crate::RegistryCredentials>,
) -> Result<RootfsLayers>;
+
+ /// Pulls `reference` for `arch` the way [`Self::resolve_rootfs`] does (the
+ /// caller's credentials, else the host's own credential chain, through
+ /// the shared layer cache) and writes it to `out` as an OCI image layout
+ /// archive that keeps every blob as the registry served it (so every
+ /// digest holds), named `reference`. Returns the platform manifest's
+ /// digest (`sha256:...`).
+ ///
+ /// A runtime that has its own image store but no way to hold a
+ /// registry credential of Cua's (Apple's `container`: its logins live in
+ /// the user's keychain) loads the archive instead of pulling itself, so
+ /// every runtime pulls with the same credentials, mirrors and cache.
+ async fn pull_oci_archive(
+ &self,
+ reference: &str,
+ arch: Arch,
+ creds: Option<&crate::RegistryCredentials>,
+ out: &std::path::Path,
+ ) -> Result<String> {
+ let _ = (reference, arch, creds, out);
+ Err(crate::VmmError::Unsupported {
+ backend: "image resolver",
+ op: "OCI archives",
+ })
+ }
}
/// A checkpoint as files, for copying it to another host.
diff --git a/libs/cua/crates/cua-vmm/tests/containerization.rs b/libs/cua/crates/cua-vmm/tests/containerization.rs
index 34f124b444..971d5ec110 100644
--- a/libs/cua/crates/cua-vmm/tests/containerization.rs
+++ b/libs/cua/crates/cua-vmm/tests/containerization.rs
@@ -360,3 +360,280 @@ async fn a_pool_member_is_claimed_under_the_spaces_name() {
rt.start(&spec("space-1")).await.unwrap();
assert_eq!(rt.status("space-1").await.unwrap(), Status::Running);
}
+
+// ---- Images, registry credentials and guest DNS ----------------------------
+
+use async_trait::async_trait;
+use cua_vmm::{Arch, OciRunConfig, RegistryCredentials, RootfsLayers, RootfsResolver};
+use std::sync::{Arc, Mutex};
+
+/// A resolver that serves one image digest and writes the fake archive
+/// (`IMAGE=` and `DIGEST=` lines) `container image load` reads, remembering
+/// which credential each call carried.
+struct FakeResolver {
+ digest: String,
+ seen: Mutex<Vec<(String, Option<String>)>>,
+}
+
+impl FakeResolver {
+ fn new(digest: &str) -> Arc<Self> {
+ Arc::new(Self {
+ digest: digest.into(),
+ seen: Mutex::new(vec![]),
+ })
+ }
+
+ fn calls(&self) -> Vec<(String, Option<String>)> {
+ self.seen.lock().unwrap().clone()
+ }
+}
+
+#[async_trait]
+impl RootfsResolver for FakeResolver {
+ async fn resolve_rootfs(
+ &self,
+ reference: &str,
+ _arch: Arch,
+ creds: Option<&RegistryCredentials>,
+ ) -> cua_vmm::Result<RootfsLayers> {
+ self.seen.lock().unwrap().push((
+ format!("resolve {reference}"),
+ creds.map(|c| c.username.clone()),
+ ));
+ Ok(RootfsLayers {
+ digest: self.digest.clone(),
+ layers: vec![],
+ config: OciRunConfig::default(),
+ })
+ }
+
+ async fn pull_oci_archive(
+ &self,
+ reference: &str,
+ _arch: Arch,
+ creds: Option<&RegistryCredentials>,
+ out: &std::path::Path,
+ ) -> cua_vmm::Result<String> {
+ self.seen.lock().unwrap().push((
+ format!("archive {reference}"),
+ creds.map(|c| c.username.clone()),
+ ));
+ std::fs::write(out, format!("IMAGE={reference}\nDIGEST={}\n", self.digest))?;
+ Ok(self.digest.clone())
+ }
+}
+
+const PRIVATE: &str = "ghcr.io/acme/private-image:1";
+
+fn private_spec(name: &str) -> StartSpec {
+ let mut s = spec(name);
+ s.image = ImageSource::oci(PRIVATE);
+ s
+}
+
+/// A private image `container` cannot pull anonymously (it refuses the
+/// token exchange) is pulled through the shared puller with the host-held
+/// credential, loaded as an archive, and run: the credential never reaches
+/// a `container` command line, and the archive is gone afterwards.
+#[tokio::test]
+async fn a_private_image_is_pulled_with_the_host_held_credential() {
+ let f = FakeContainer::new();
+ f.make_private(PRIVATE);
+ let resolver = FakeResolver::new("sha256:private1");
+ let rt = f.runtime_with(resolver.clone());
+ let mut s = private_spec("sb-priv");
+ s.registry_auth =
+ Some(RegistryCredentials::new("the-user", "s3cret-token").for_registry("ghcr.io"));
+ let inst = rt.start(&s).await.unwrap();
+ assert_eq!(inst.status, Status::Running);
+
+ // The resolver was asked with the credential: once while Apple's
+ // services came up for the first time (the layers download meanwhile),
+ // once to check the registry, once to pack the archive.
+ assert_eq!(
+ resolver.calls(),
+ vec![
+ (format!("resolve {PRIVATE}"), Some("the-user".to_string())),
+ (format!("resolve {PRIVATE}"), Some("the-user".to_string())),
+ (format!("archive {PRIVATE}"), Some("the-user".to_string())),
+ ]
+ );
+ // Later starts, with the services up, do not prefetch.
+ let before = resolver.calls().len();
+ rt.start(&private_spec("sb-priv-2")).await.unwrap();
+ let new_calls = &resolver.calls()[before..];
+ assert!(
+ new_calls
+ .iter()
+ .filter(|(c, _)| c.starts_with("resolve"))
+ .count()
+ <= 1,
+ "{new_calls:?}"
+ );
+ let calls = f.calls();
+ let load = calls
+ .iter()
+ .position(|c| c.starts_with("image load --input "))
+ .unwrap_or_else(|| panic!("{calls:#?}"));
+ let run = calls.iter().position(|c| c.starts_with("run ")).unwrap();
+ assert!(load < run, "the image is loaded before it runs: {calls:#?}");
+ assert!(
+ !calls.iter().any(|c| c.starts_with("image pull")),
+ "`container` never pulls what only the shared puller may: {calls:#?}"
+ );
+ // Nothing secret on any command line, and nothing left on disk.
+ assert!(
+ calls
+ .iter()
+ .all(|c| !c.contains("s3cret-token") && !c.contains("the-user")),
+ "{calls:#?}"
+ );
+ let leftovers: Vec<_> = std::fs::read_dir(rt.config().root.join("run"))
+ .map(|d| d.flatten().map(|e| e.file_name()).collect())
+ .unwrap_or_default();
+ assert!(leftovers.is_empty(), "{leftovers:?}");
+}
+
+/// The variant the registry serves is already in the store: nothing is
+/// packed or loaded again; a moved tag is loaded.
+#[tokio::test]
+async fn an_image_already_in_the_store_is_not_loaded_again() {
+ let f = FakeContainer::new();
+ f.make_private(PRIVATE);
+ let resolver = FakeResolver::new("sha256:v1");
+ let rt = f.runtime_with(resolver.clone());
+ rt.start(&private_spec("sb-a")).await.unwrap();
+ rt.start(&private_spec("sb-b")).await.unwrap();
+ let loads = |f: &FakeContainer| {
+ f.calls()
+ .iter()
+ .filter(|c| c.starts_with("image load"))
+ .count()
+ };
+ assert_eq!(
+ loads(&f),
+ 1,
+ "the second Space finds the image: {:#?}",
+ f.calls()
+ );
+ let archives = resolver
+ .calls()
+ .iter()
+ .filter(|(c, _)| c.starts_with("archive"))
+ .count();
+ assert_eq!(archives, 1);
+
+ // The tag moved: the registry now serves another digest.
+ let moved = FakeResolver::new("sha256:v2");
+ let rt2 = f.runtime_with(moved);
+ rt2.start(&private_spec("sb-c")).await.unwrap();
+ assert_eq!(loads(&f), 2, "{:#?}", f.calls());
+}
+
+/// Without a resolver `container` pulls by itself, anonymously: a private
+/// image then fails in plain words, saying how to give Cua the credential.
+#[tokio::test]
+async fn a_private_image_without_credentials_says_how_to_sign_in() {
+ let f = FakeContainer::new();
+ f.make_private(PRIVATE);
+ let mut s = private_spec("sb-nocred");
+ // The injected spacesd path pulls explicitly (to read the run config).
+ s.inject_spacesd = Some(f.dir.path().join("container"));
+ let e = f.runtime().start(&s).await.unwrap_err().to_string();
+ assert!(e.contains("private or needs a registry sign-in"), "{e}");
+ assert!(e.contains("CUA_REGISTRY_USERNAME"), "{e}");
+ assert!(!e.contains("insecure credential exchange"), "{e}");
+ assert!(!f.calls().iter().any(|c| c.starts_with("run ")));
+}
+
+/// When the shared puller cannot get the image either, its reason (the
+/// registry's, in plain words) is what the caller sees, and a credential
+/// handed to the Space is never silently dropped for an anonymous pull.
+#[tokio::test]
+async fn a_failed_pull_with_a_credential_is_not_retried_anonymously() {
+ struct Refuses;
+ #[async_trait]
+ impl RootfsResolver for Refuses {
+ async fn resolve_rootfs(
+ &self,
+ reference: &str,
+ _: Arch,
+ _: Option<&RegistryCredentials>,
+ ) -> cua_vmm::Result<RootfsLayers> {
+ Err(cua_vmm::VmmError::other(format!(
+ "{reference}: not authorized: this token cannot read the package"
+ )))
+ }
+ }
+ let f = FakeContainer::new();
+ let rt = f.runtime_with(Arc::new(Refuses));
+ let mut s = spec("sb-denied");
+ s.registry_auth = Some(RegistryCredentials::new("u", "p"));
+ let e = rt.start(&s).await.unwrap_err().to_string();
+ assert!(e.contains("this token cannot read the package"), "{e}");
+ assert!(
+ !f.calls()
+ .iter()
+ .any(|c| c.starts_with("image pull") || c.starts_with("run ")),
+ "{:#?}",
+ f.calls()
+ );
+}
+
+/// A guest never gets vmnet's resolver (it answers AAAA with the truncated
+/// bit set and serves no TCP, so name lookups for both families failed): it
+/// is given the host's resolvers and a public fallback.
+#[tokio::test]
+async fn a_guest_is_given_resolvers_that_answer() {
+ let f = FakeContainer::new();
+ let rt = f.runtime();
+ rt.start(&spec("sb-dns")).await.unwrap();
+ let run = f
+ .calls()
+ .into_iter()
+ .find(|c| c.starts_with("run "))
+ .unwrap();
+ assert!(run.contains("--dns "), "{run}");
+ let dns = f.file("c/sb-dns.dns").unwrap();
+ let servers: Vec<&str> = dns.split(',').collect();
+ assert!(servers.contains(&"8.8.8.8"), "{dns}");
+ assert!(
+ servers
+ .iter()
+ .all(|s| !s.starts_with("127.") && !s.starts_with("169.254.")),
+ "{dns}"
+ );
+}
+
+/// A digest names one image for good: once the store has it, a start does
+/// not ask the registry again (three requests on every start), while a tag
+/// is checked every time (it may have moved).
+#[tokio::test]
+async fn a_digest_pinned_image_in_the_store_is_not_asked_of_the_registry_again() {
+ let f = FakeContainer::new();
+ let resolver = FakeResolver::new("sha256:pinned1");
+ let rt = f.runtime_with(resolver.clone());
+ let pinned = format!("ghcr.io/trycua/linux@sha256:{}", "ab".repeat(32));
+ let mut s = spec("sb-pin1");
+ s.image = ImageSource::oci(pinned.clone());
+ rt.start(&s).await.unwrap();
+ let asked = |r: &FakeResolver| r.calls().len();
+ let first = asked(&resolver);
+ assert!(first >= 2, "the first start pulls: {:?}", resolver.calls());
+ let mut s2 = spec("sb-pin2");
+ s2.image = ImageSource::oci(pinned);
+ rt.start(&s2).await.unwrap();
+ assert_eq!(
+ asked(&resolver),
+ first,
+ "the second start finds the digest in the store: {:?}",
+ resolver.calls()
+ );
+ // A tag is looked up every time.
+ let tag = FakeResolver::new("sha256:t1");
+ let rt2 = f.runtime_with(tag.clone());
+ rt2.start(&spec("sb-tag1")).await.unwrap();
+ let after_first = tag.calls().len();
+ rt2.start(&spec("sb-tag2")).await.unwrap();
+ assert!(tag.calls().len() > after_first, "{:?}", tag.calls());
+}
diff --git a/libs/cua/crates/cua-vmm/tests/support/fake_container.rs b/libs/cua/crates/cua-vmm/tests/support/fake_container.rs
index 2702bd7056..fe1e587633 100644
--- a/libs/cua/crates/cua-vmm/tests/support/fake_container.rs
+++ b/libs/cua/crates/cua-vmm/tests/support/fake_container.rs
@@ -4,6 +4,7 @@
use std::path::{Path, PathBuf};
+use cua_vmm::RootfsResolver;
use cua_vmm::containerization::{ContainerizationConfig, ContainerizationRuntime};
const SCRIPT: &str = r#"
@@ -38,16 +39,17 @@ cmd="$1"; shift
mkdir -p "$S/c"
case "$cmd" in
run)
- ports=""; labels=""; name=""; envf=""; ep=""
+ ports=""; labels=""; name=""; envf=""; ep=""; dns=""
while [ $# -gt 0 ]; do
case "$1" in
- --detach|--progress|--name|--cpus|--memory|--shm-size|--cap-add|--label|--env-file|--publish|--entrypoint|--arch) ;;
+ --detach|--progress|--name|--cpus|--memory|--shm-size|--cap-add|--label|--env-file|--publish|--entrypoint|--arch|--dns) ;;
*) break ;;
esac
case "$1" in
--detach) shift; continue ;;
--name) name="$2" ;;
--env-file) envf="$2" ;;
+ --dns) dns="${dns:+$dns,}$2" ;;
--entrypoint) ep="$2" ;;
--label) k="${2%%=*}"; v="${2#*=}"; labels="${labels:+$labels,}\"$k\":\"$v\"" ;;
--publish) spec="${2%/tcp}"; rest="${spec#*:}"; h="${rest%%:*}"; g="${rest#*:}"
@@ -56,7 +58,13 @@ case "$cmd" in
shift 2
done
image="$1"
+ # `container run` pulls a missing image by itself, anonymously.
+ k=$(printf '%s' "$image" | tr '/:@' '___')
+ if [ -f "$S/private/$k" ] && [ ! -f "$S/img/$k" ]; then
+ echo "Error: refusing insecure credential exchange: authorization server https://ghcr.io/token issued its own authentication challenge" >&2; exit 1
+ fi
if [ -f "$S/c/$name.image" ]; then echo "Error: container $name already exists" >&2; exit 1; fi
+ printf '%s' "$dns" > "$S/c/$name.dns"
printf '%s' "$image" > "$S/c/$name.image"
printf '%s' "$ports" > "$S/c/$name.ports"
printf '%s' "$labels" > "$S/c/$name.labels"
@@ -82,6 +90,31 @@ case "$cmd" in
stop) [ "$1" = "--time" ] && shift 2; printf stopped > "$S/c/$1.state" ;;
start) [ -f "$S/c/$1.image" ] || exit 1; printf running > "$S/c/$1.state" ;;
delete) [ "$1" = "--force" ] && shift; rm -f "$S/c/$1".* ;;
+ image)
+ sub="$1"; shift
+ key() { printf '%s' "$1" | tr '/:@' '___'; }
+ mkdir -p "$S/img"
+ case "$sub" in
+ pull)
+ while [ $# -gt 0 ]; do case "$1" in --progress|--arch|--scheme) shift 2 ;; *) break ;; esac; done
+ image="$1"
+ if [ -f "$S/private/$(key "$image")" ] && [ ! -f "$S/img/$(key "$image")" ]; then
+ echo "Error: refusing insecure credential exchange: authorization server https://ghcr.io/token issued its own authentication challenge" >&2; exit 1
+ fi
+ [ -f "$S/img/$(key "$image")" ] || printf 'sha256:pulled' > "$S/img/$(key "$image")"
+ echo "$image" ;;
+ load)
+ [ "$1" = "--input" ] || { echo "load: no --input" >&2; exit 2; }
+ # The fake archive: IMAGE=<ref> and DIGEST=<d> lines.
+ ref=$(sed -n 's/^IMAGE=//p' "$2"); dg=$(sed -n 's/^DIGEST=//p' "$2")
+ [ -n "$ref" ] || { echo "Error: not an OCI archive" >&2; exit 1; }
+ printf '%s' "$dg" > "$S/img/$(key "$ref")"
+ echo "$ref" ;;
+ inspect)
+ [ -f "$S/img/$(key "$1")" ] || { echo "Error: image not found: $1" >&2; exit 1; }
+ printf '[{"id":"i","variants":[{"digest":"%s","platform":{"architecture":"arm64","os":"linux"},"config":{"architecture":"arm64","config":{"Cmd":["/bin/true"],"User":"cua"}}}]}]\n' "$(cat "$S/img/$(key "$1")")" ;;
+ *) echo "fake container: unknown image command $sub" >&2; exit 2 ;;
+ esac ;;
logs) echo "boot failed: no init" ;;
exec)
[ "$1" = "--interactive" ] && shift
@@ -134,9 +167,34 @@ impl FakeContainer {
bin: Some(self.dir.path().join("container")),
auto_install: false,
graceful_stop: std::time::Duration::from_secs(1),
+ resolver: None,
})
}
+ /// [`Self::runtime`] with a resolver (images are pulled through it).
+ pub fn runtime_with(
+ &self,
+ resolver: std::sync::Arc<dyn RootfsResolver>,
+ ) -> ContainerizationRuntime {
+ ContainerizationRuntime::new(ContainerizationConfig {
+ root: self.root(),
+ bin: Some(self.dir.path().join("container")),
+ auto_install: false,
+ graceful_stop: std::time::Duration::from_secs(1),
+ resolver: Some(resolver),
+ })
+ }
+
+ /// Makes `image` private: `container` cannot pull it anonymously.
+ pub fn make_private(&self, image: &str) {
+ std::fs::create_dir_all(self.state().join("private")).unwrap();
+ let key: String = image
+ .chars()
+ .map(|c| if matches!(c, '/' | ':' | '@') { '_' } else { c })
+ .collect();
+ std::fs::write(self.state().join("private").join(key), "").unwrap();
+ }
+
/// Every call, one line each (`args | APP_ROOT=...`).
pub fn calls(&self) -> Vec<String> {
std::fs::read_to_string(self.state().join("calls"))