Skip to main content

unkernel_rs/
oci.rs

1//! Zero-daemon OCI / Docker Registry v2 image puller & layer unpacker.
2//!
3//! Pulls public OCI/Docker images (Docker Hub, GHCR, Quay, Harbor) over HTTPS in pure Rust,
4//! selects the `linux/arm64` (or requested architecture) manifest from multi-arch indexes,
5//! unpacks gzip/plain tar layers with OCI whiteout handling into a local cache directory, and
6//! returns the cached rootfs path ready to be mounted `:cow` at `/mnt/oci`.
7
8use flate2::read::GzDecoder;
9use serde::{Deserialize, Serialize};
10use sha2::{Digest, Sha256};
11use std::collections::BTreeMap;
12use std::fs::{self, File};
13use std::io::Read;
14use std::path::{Component, Path, PathBuf};
15use wasmtime::{Result, bail, format_err};
16
17const ACCEPT_MANIFEST: &str = concat!(
18    "application/vnd.oci.image.index.v1+json, ",
19    "application/vnd.docker.distribution.manifest.list.v2+json, ",
20    "application/vnd.oci.image.manifest.v1+json, ",
21    "application/vnd.docker.distribution.manifest.v2+json"
22);
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ImageRef {
26    pub registry: String,
27    pub repository: String,
28    pub reference: String,
29}
30
31#[derive(Debug, Clone, Default, Serialize, Deserialize)]
32pub struct OciImageConfig {
33    #[serde(default)]
34    pub env: BTreeMap<String, String>,
35    #[serde(default)]
36    pub working_dir: Option<String>,
37}
38
39#[derive(Debug, Clone)]
40pub struct OciRootfs {
41    pub rootfs_dir: PathBuf,
42    pub config: OciImageConfig,
43    pub from_cache: bool,
44}
45
46/// Parse a Docker/OCI image reference (e.g. `alpine:3.21`, `python:3.13-alpine`, `ghcr.io/org/app:v1`).
47pub fn parse_image_ref(raw: &str) -> Result<ImageRef> {
48    let raw = raw.trim();
49    if raw.is_empty() {
50        bail!("empty OCI image reference");
51    }
52
53    // Split digest or tag
54    let (name_part, reference) = if let Some((n, d)) = raw.split_once('@') {
55        (n, d.to_string())
56    } else if let Some(colon) = raw.rfind(':') {
57        let after = &raw[colon + 1..];
58        if !after.contains('/') {
59            (&raw[..colon], after.to_string())
60        } else {
61            (raw, "latest".to_string())
62        }
63    } else {
64        (raw, "latest".to_string())
65    };
66
67    let (registry, repository) = match name_part.split_once('/') {
68        Some((first, rest))
69            if first.contains('.') || first.contains(':') || first == "localhost" =>
70        {
71            let reg = if first == "docker.io" || first == "index.docker.io" {
72                "registry-1.docker.io".to_string()
73            } else {
74                first.to_string()
75            };
76            let repo = if reg == "registry-1.docker.io" && !rest.contains('/') {
77                format!("library/{rest}")
78            } else {
79                rest.to_string()
80            };
81            (reg, repo)
82        }
83        Some(_) => ("registry-1.docker.io".to_string(), name_part.to_string()),
84        None => (
85            "registry-1.docker.io".to_string(),
86            format!("library/{name_part}"),
87        ),
88    };
89
90    Ok(ImageRef {
91        registry,
92        repository,
93        reference,
94    })
95}
96
97fn parse_www_authenticate(header: &str) -> Option<(String, Option<String>, Option<String>)> {
98    let rest = header
99        .strip_prefix("Bearer ")
100        .or_else(|| header.strip_prefix("bearer "))?;
101    let mut realm = None;
102    let mut service = None;
103    let mut scope = None;
104    for part in rest.split(',') {
105        let part = part.trim();
106        if let Some((k, v)) = part.split_once('=') {
107            let val = v.trim().trim_matches('"').to_string();
108            match k.trim() {
109                "realm" => realm = Some(val),
110                "service" => service = Some(val),
111                "scope" => scope = Some(val),
112                _ => {}
113            }
114        }
115    }
116    Some((realm?, service, scope))
117}
118
119fn fetch_bearer_token(www_auth: &str) -> Result<String> {
120    let (realm, service, scope) = parse_www_authenticate(www_auth)
121        .ok_or_else(|| format_err!("unsupported WWW-Authenticate header: {www_auth}"))?;
122    let mut url = realm;
123    let mut sep = if url.contains('?') { '&' } else { '?' };
124    if let Some(svc) = service {
125        url.push(sep);
126        url.push_str("service=");
127        url.push_str(&svc);
128        sep = '&';
129    }
130    if let Some(sc) = scope {
131        url.push(sep);
132        url.push_str("scope=");
133        url.push_str(&sc);
134    }
135    let resp = ureq::get(&url)
136        .call()
137        .map_err(|e| format_err!("OCI token request {url}: {e}"))?;
138    let body: serde_json::Value = serde_json::from_reader(resp.into_reader())
139        .map_err(|e| format_err!("OCI token JSON: {e}"))?;
140    body.get("token")
141        .or_else(|| body.get("access_token"))
142        .and_then(|v| v.as_str())
143        .map(ToString::to_string)
144        .ok_or_else(|| format_err!("OCI token response missing token field"))
145}
146
147fn oci_get(url: &str, accept: Option<&str>, token: &mut Option<String>) -> Result<ureq::Response> {
148    let make_req = |tok: &Option<String>| {
149        let mut req = ureq::get(url);
150        if let Some(a) = accept {
151            req = req.set("Accept", a);
152        }
153        if let Some(t) = tok {
154            req = req.set("Authorization", &format!("Bearer {t}"));
155        }
156        req
157    };
158
159    match make_req(token).call() {
160        Ok(resp) => Ok(resp),
161        Err(ureq::Error::Status(401, resp)) => {
162            let www = resp
163                .header("www-authenticate")
164                .or_else(|| resp.header("WWW-Authenticate"))
165                .ok_or_else(|| format_err!("401 from {url} without WWW-Authenticate header"))?;
166            let new_tok = fetch_bearer_token(www)?;
167            *token = Some(new_tok);
168            make_req(token)
169                .call()
170                .map_err(|e| format_err!("OCI GET {url} after auth: {e}"))
171        }
172        Err(e) => Err(format_err!("OCI GET {url}: {e}")),
173    }
174}
175
176fn sanitize_rel_path(raw: &Path) -> Option<PathBuf> {
177    let mut out = PathBuf::new();
178    for comp in raw.components() {
179        match comp {
180            Component::Normal(s) => out.push(s),
181            Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
182            Component::ParentDir => {
183                out.pop();
184            }
185        }
186    }
187    if out.as_os_str().is_empty() {
188        None
189    } else {
190        Some(out)
191    }
192}
193
194fn unpack_layer_tar<R: Read>(reader: R, rootfs: &Path) -> Result<()> {
195    let mut archive = tar::Archive::new(reader);
196    archive.set_preserve_permissions(true);
197    archive.set_preserve_mtime(false);
198
199    for entry in archive.entries()? {
200        let mut entry = entry?;
201        let raw_path = entry.path()?.into_owned();
202        let Some(rel) = sanitize_rel_path(&raw_path) else {
203            continue;
204        };
205
206        // Handle OCI whiteouts (.wh.<name> and opaque dir .wh..wh..opq)
207        if let Some(fname) = rel.file_name().and_then(|s| s.to_str()) {
208            if fname == ".wh..wh..opq" {
209                if let Some(parent) = rel.parent() {
210                    let dir = rootfs.join(parent);
211                    if dir.is_dir() {
212                        for child in fs::read_dir(&dir)? {
213                            let child = child?;
214                            let p = child.path();
215                            if p.is_dir() {
216                                let _ = fs::remove_dir_all(&p);
217                            } else {
218                                let _ = fs::remove_file(&p);
219                            }
220                        }
221                    }
222                }
223                continue;
224            }
225            if let Some(target_name) = fname.strip_prefix(".wh.") {
226                let target = match rel.parent() {
227                    Some(p) => rootfs.join(p).join(target_name),
228                    None => rootfs.join(target_name),
229                };
230                if target.is_dir() {
231                    let _ = fs::remove_dir_all(&target);
232                } else {
233                    let _ = fs::remove_file(&target);
234                }
235                continue;
236            }
237        }
238
239        let dst = rootfs.join(&rel);
240        if let Some(parent) = dst.parent() {
241            fs::create_dir_all(parent)?;
242        }
243
244        let etype = entry.header().entry_type();
245        if etype.is_dir() {
246            fs::create_dir_all(&dst)?;
247        } else if etype.is_file() {
248            if dst.exists() || dst.symlink_metadata().is_ok() {
249                let _ = fs::remove_file(&dst);
250            }
251            let mut out = File::create(&dst)?;
252            std::io::copy(&mut entry, &mut out)?;
253            #[cfg(unix)]
254            {
255                use std::os::unix::fs::PermissionsExt;
256                if let Ok(mode) = entry.header().mode() {
257                    let _ = fs::set_permissions(&dst, fs::Permissions::from_mode(mode & 0o777));
258                }
259            }
260        } else if etype.is_symlink() {
261            if let Ok(Some(link_target)) = entry.link_name() {
262                if dst.symlink_metadata().is_ok() {
263                    let _ = fs::remove_file(&dst);
264                }
265                #[cfg(unix)]
266                {
267                    let _ = std::os::unix::fs::symlink(&link_target, &dst);
268                }
269            }
270        } else if etype.is_hard_link()
271            && let Ok(Some(link_target)) = entry.link_name()
272            && let Some(rel_target) = sanitize_rel_path(&link_target)
273        {
274            let src = rootfs.join(rel_target);
275            if src.exists() {
276                if dst.symlink_metadata().is_ok() {
277                    let _ = fs::remove_file(&dst);
278                }
279                if fs::hard_link(&src, &dst).is_err() {
280                    let _ = fs::copy(&src, &dst);
281                }
282            }
283        }
284    }
285    Ok(())
286}
287
288/// Fetch (or load from cache) an OCI/Docker image rootfs for the given architecture (`"arm64"`).
289pub fn fetch_oci_rootfs(
290    image_ref: &str,
291    arch: &str,
292    cache_dir: &Path,
293    offline: bool,
294) -> Result<OciRootfs> {
295    let parsed = parse_image_ref(image_ref)?;
296    let mut hasher = Sha256::new();
297    hasher.update(
298        format!(
299            "{}/{}:{}@{}",
300            parsed.registry, parsed.repository, parsed.reference, arch
301        )
302        .as_bytes(),
303    );
304    let key = format!("{:x}", hasher.finalize());
305    let img_dir = cache_dir.join("oci").join(&key[..24]);
306    let rootfs_dir = img_dir.join("rootfs");
307    let ready_marker = img_dir.join(".ready");
308    let cfg_path = img_dir.join("config.json");
309
310    if ready_marker.exists() && rootfs_dir.is_dir() {
311        let config: OciImageConfig = fs::read_to_string(&cfg_path)
312            .ok()
313            .and_then(|s| serde_json::from_str(&s).ok())
314            .unwrap_or_default();
315        return Ok(OciRootfs {
316            rootfs_dir,
317            config,
318            from_cache: true,
319        });
320    }
321
322    if offline {
323        bail!(
324            "OCI image {image_ref:?} is not cached at {} and offline=true",
325            rootfs_dir.display()
326        );
327    }
328
329    fs::create_dir_all(&img_dir)?;
330    let mut token: Option<String> = None;
331    let base = format!("https://{}/v2/{}", parsed.registry, parsed.repository);
332
333    // 1. Fetch manifest (or multi-arch manifest list / OCI index)
334    let manifest_url = format!("{base}/manifests/{}", parsed.reference);
335    let mut manifest: serde_json::Value = serde_json::from_reader(
336        oci_get(&manifest_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
337    )
338    .map_err(|e| format_err!("parse OCI manifest JSON: {e}"))?;
339
340    if let Some(manifests) = manifest.get("manifests").and_then(|v| v.as_array()) {
341        let chosen = manifests
342            .iter()
343            .find(|m| {
344                let plat = m.get("platform");
345                plat.and_then(|p| p.get("os")).and_then(|v| v.as_str()) == Some("linux")
346                    && plat
347                        .and_then(|p| p.get("architecture"))
348                        .and_then(|v| v.as_str())
349                        == Some(arch)
350            })
351            .or_else(|| manifests.first())
352            .ok_or_else(|| format_err!("OCI index for {image_ref} has no manifests"))?;
353        let digest = chosen
354            .get("digest")
355            .and_then(|v| v.as_str())
356            .ok_or_else(|| format_err!("OCI index entry missing digest"))?;
357        let child_url = format!("{base}/manifests/{digest}");
358        manifest = serde_json::from_reader(
359            oci_get(&child_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
360        )
361        .map_err(|e| format_err!("parse child OCI manifest JSON: {e}"))?;
362    }
363
364    // 2. Fetch optional image config blob (env, workdir)
365    let mut img_cfg = OciImageConfig::default();
366    if let Some(cfg_digest) = manifest
367        .get("config")
368        .and_then(|c| c.get("digest"))
369        .and_then(|v| v.as_str())
370    {
371        let cfg_url = format!("{base}/blobs/{cfg_digest}");
372        if let Ok(resp) = oci_get(&cfg_url, None, &mut token)
373            && let Ok(val) = serde_json::from_reader::<_, serde_json::Value>(resp.into_reader())
374            && let Some(c) = val.get("config")
375        {
376            if let Some(envs) = c.get("Env").and_then(|v| v.as_array()) {
377                for e in envs.iter().filter_map(|v| v.as_str()) {
378                    if let Some((k, v)) = e.split_once('=') {
379                        img_cfg.env.insert(k.to_string(), v.to_string());
380                    }
381                }
382            }
383            if let Some(wd) = c.get("WorkingDir").and_then(|v| v.as_str())
384                && !wd.is_empty()
385            {
386                img_cfg.working_dir = Some(wd.to_string());
387            }
388        }
389    }
390
391    // 3. Download and unpack each layer in order into a staging directory
392    let layers = manifest
393        .get("layers")
394        .and_then(|v| v.as_array())
395        .ok_or_else(|| format_err!("OCI manifest for {image_ref} missing layers array"))?;
396
397    let tmp_rootfs = img_dir.join("rootfs.tmp");
398    if tmp_rootfs.exists() {
399        let _ = fs::remove_dir_all(&tmp_rootfs);
400    }
401    fs::create_dir_all(&tmp_rootfs)?;
402
403    for layer in layers {
404        let digest = layer
405            .get("digest")
406            .and_then(|v| v.as_str())
407            .ok_or_else(|| format_err!("OCI layer missing digest"))?;
408        let media_type = layer
409            .get("mediaType")
410            .and_then(|v| v.as_str())
411            .unwrap_or("");
412        let blob_url = format!("{base}/blobs/{digest}");
413        let resp = oci_get(&blob_url, None, &mut token)?;
414        let reader = resp.into_reader();
415        if media_type.contains("gzip") || media_type.ends_with("+gzip") || media_type.is_empty() {
416            unpack_layer_tar(GzDecoder::new(reader), &tmp_rootfs)?;
417        } else {
418            unpack_layer_tar(reader, &tmp_rootfs)?;
419        }
420    }
421
422    // Ensure standard mount points exist for chroot bind mounts
423    for d in ["proc", "dev", "sys", "tmp", "etc/ssl/certs"] {
424        let _ = fs::create_dir_all(tmp_rootfs.join(d));
425    }
426
427    if rootfs_dir.exists() {
428        let _ = fs::remove_dir_all(&rootfs_dir);
429    }
430    fs::rename(&tmp_rootfs, &rootfs_dir)?;
431    fs::write(&cfg_path, serde_json::to_vec_pretty(&img_cfg)?)?;
432    fs::write(&ready_marker, format!("{image_ref}\n"))?;
433
434    Ok(OciRootfs {
435        rootfs_dir,
436        config: img_cfg,
437        from_cache: false,
438    })
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    #[test]
446    fn parses_docker_and_oci_image_refs() {
447        let a = parse_image_ref("alpine:3.21").unwrap();
448        assert_eq!(a.registry, "registry-1.docker.io");
449        assert_eq!(a.repository, "library/alpine");
450        assert_eq!(a.reference, "3.21");
451
452        let b = parse_image_ref("python").unwrap();
453        assert_eq!(b.registry, "registry-1.docker.io");
454        assert_eq!(b.repository, "library/python");
455        assert_eq!(b.reference, "latest");
456
457        let c = parse_image_ref("ghcr.io/njannasch/app:v1.2").unwrap();
458        assert_eq!(c.registry, "ghcr.io");
459        assert_eq!(c.repository, "njannasch/app");
460        assert_eq!(c.reference, "v1.2");
461    }
462}