use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use wasmtime::{Result, bail, format_err};
const ACCEPT_MANIFEST: &str = concat!(
"application/vnd.oci.image.index.v1+json, ",
"application/vnd.docker.distribution.manifest.list.v2+json, ",
"application/vnd.oci.image.manifest.v1+json, ",
"application/vnd.docker.distribution.manifest.v2+json"
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageRef {
pub registry: String,
pub repository: String,
pub reference: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OciImageConfig {
#[serde(default)]
pub env: BTreeMap<String, String>,
#[serde(default)]
pub working_dir: Option<String>,
}
#[derive(Debug, Clone)]
pub struct OciRootfs {
pub rootfs_dir: PathBuf,
pub config: OciImageConfig,
pub from_cache: bool,
}
pub fn parse_image_ref(raw: &str) -> Result<ImageRef> {
let raw = raw.trim();
if raw.is_empty() {
bail!("empty OCI image reference");
}
let (name_part, reference) = if let Some((n, d)) = raw.split_once('@') {
(n, d.to_string())
} else if let Some(colon) = raw.rfind(':') {
let after = &raw[colon + 1..];
if !after.contains('/') {
(&raw[..colon], after.to_string())
} else {
(raw, "latest".to_string())
}
} else {
(raw, "latest".to_string())
};
let (registry, repository) = match name_part.split_once('/') {
Some((first, rest))
if first.contains('.') || first.contains(':') || first == "localhost" =>
{
let reg = if first == "docker.io" || first == "index.docker.io" {
"registry-1.docker.io".to_string()
} else {
first.to_string()
};
let repo = if reg == "registry-1.docker.io" && !rest.contains('/') {
format!("library/{rest}")
} else {
rest.to_string()
};
(reg, repo)
}
Some(_) => ("registry-1.docker.io".to_string(), name_part.to_string()),
None => (
"registry-1.docker.io".to_string(),
format!("library/{name_part}"),
),
};
Ok(ImageRef {
registry,
repository,
reference,
})
}
fn parse_www_authenticate(header: &str) -> Option<(String, Option<String>, Option<String>)> {
let rest = header
.strip_prefix("Bearer ")
.or_else(|| header.strip_prefix("bearer "))?;
let mut realm = None;
let mut service = None;
let mut scope = None;
for part in rest.split(',') {
let part = part.trim();
if let Some((k, v)) = part.split_once('=') {
let val = v.trim().trim_matches('"').to_string();
match k.trim() {
"realm" => realm = Some(val),
"service" => service = Some(val),
"scope" => scope = Some(val),
_ => {}
}
}
}
Some((realm?, service, scope))
}
fn fetch_bearer_token(www_auth: &str) -> Result<String> {
let (realm, service, scope) = parse_www_authenticate(www_auth)
.ok_or_else(|| format_err!("unsupported WWW-Authenticate header: {www_auth}"))?;
let mut url = realm;
let mut sep = if url.contains('?') { '&' } else { '?' };
if let Some(svc) = service {
url.push(sep);
url.push_str("service=");
url.push_str(&svc);
sep = '&';
}
if let Some(sc) = scope {
url.push(sep);
url.push_str("scope=");
url.push_str(&sc);
}
let resp = ureq::get(&url)
.call()
.map_err(|e| format_err!("OCI token request {url}: {e}"))?;
let body: serde_json::Value = serde_json::from_reader(resp.into_reader())
.map_err(|e| format_err!("OCI token JSON: {e}"))?;
body.get("token")
.or_else(|| body.get("access_token"))
.and_then(|v| v.as_str())
.map(ToString::to_string)
.ok_or_else(|| format_err!("OCI token response missing token field"))
}
fn oci_get(url: &str, accept: Option<&str>, token: &mut Option<String>) -> Result<ureq::Response> {
let make_req = |tok: &Option<String>| {
let mut req = ureq::get(url);
if let Some(a) = accept {
req = req.set("Accept", a);
}
if let Some(t) = tok {
req = req.set("Authorization", &format!("Bearer {t}"));
}
req
};
match make_req(token).call() {
Ok(resp) => Ok(resp),
Err(ureq::Error::Status(401, resp)) => {
let www = resp
.header("www-authenticate")
.or_else(|| resp.header("WWW-Authenticate"))
.ok_or_else(|| format_err!("401 from {url} without WWW-Authenticate header"))?;
let new_tok = fetch_bearer_token(www)?;
*token = Some(new_tok);
make_req(token)
.call()
.map_err(|e| format_err!("OCI GET {url} after auth: {e}"))
}
Err(e) => Err(format_err!("OCI GET {url}: {e}")),
}
}
fn sanitize_rel_path(raw: &Path) -> Option<PathBuf> {
let mut out = PathBuf::new();
for comp in raw.components() {
match comp {
Component::Normal(s) => out.push(s),
Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
Component::ParentDir => {
out.pop();
}
}
}
if out.as_os_str().is_empty() {
None
} else {
Some(out)
}
}
fn unpack_layer_tar<R: Read>(reader: R, rootfs: &Path) -> Result<()> {
let mut archive = tar::Archive::new(reader);
archive.set_preserve_permissions(true);
archive.set_preserve_mtime(false);
for entry in archive.entries()? {
let mut entry = entry?;
let raw_path = entry.path()?.into_owned();
let Some(rel) = sanitize_rel_path(&raw_path) else {
continue;
};
if let Some(fname) = rel.file_name().and_then(|s| s.to_str()) {
if fname == ".wh..wh..opq" {
if let Some(parent) = rel.parent() {
let dir = rootfs.join(parent);
if dir.is_dir() {
for child in fs::read_dir(&dir)? {
let child = child?;
let p = child.path();
if p.is_dir() {
let _ = fs::remove_dir_all(&p);
} else {
let _ = fs::remove_file(&p);
}
}
}
}
continue;
}
if let Some(target_name) = fname.strip_prefix(".wh.") {
let target = match rel.parent() {
Some(p) => rootfs.join(p).join(target_name),
None => rootfs.join(target_name),
};
if target.is_dir() {
let _ = fs::remove_dir_all(&target);
} else {
let _ = fs::remove_file(&target);
}
continue;
}
}
let dst = rootfs.join(&rel);
if let Some(parent) = dst.parent() {
fs::create_dir_all(parent)?;
}
let etype = entry.header().entry_type();
if etype.is_dir() {
fs::create_dir_all(&dst)?;
} else if etype.is_file() {
if dst.exists() || dst.symlink_metadata().is_ok() {
let _ = fs::remove_file(&dst);
}
let mut out = File::create(&dst)?;
std::io::copy(&mut entry, &mut out)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(mode) = entry.header().mode() {
let _ = fs::set_permissions(&dst, fs::Permissions::from_mode(mode & 0o777));
}
}
} else if etype.is_symlink() {
#[cfg(unix)]
if let Ok(Some(link_target)) = entry.link_name() {
if dst.symlink_metadata().is_ok() {
let _ = fs::remove_file(&dst);
}
let _ = std::os::unix::fs::symlink(&link_target, &dst);
}
} else if etype.is_hard_link()
&& let Ok(Some(link_target)) = entry.link_name()
&& let Some(rel_target) = sanitize_rel_path(&link_target)
{
let src = rootfs.join(rel_target);
if src.exists() {
if dst.symlink_metadata().is_ok() {
let _ = fs::remove_file(&dst);
}
if fs::hard_link(&src, &dst).is_err() {
let _ = fs::copy(&src, &dst);
}
}
}
}
Ok(())
}
pub fn fetch_oci_rootfs(
image_ref: &str,
arch: &str,
cache_dir: &Path,
offline: bool,
) -> Result<OciRootfs> {
let parsed = parse_image_ref(image_ref)?;
let mut hasher = Sha256::new();
hasher.update(
format!(
"{}/{}:{}@{}",
parsed.registry, parsed.repository, parsed.reference, arch
)
.as_bytes(),
);
let key = format!("{:x}", hasher.finalize());
let img_dir = cache_dir.join("oci").join(&key[..24]);
let rootfs_dir = img_dir.join("rootfs");
let ready_marker = img_dir.join(".ready");
let cfg_path = img_dir.join("config.json");
if ready_marker.exists() && rootfs_dir.is_dir() {
let config: OciImageConfig = fs::read_to_string(&cfg_path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
return Ok(OciRootfs {
rootfs_dir,
config,
from_cache: true,
});
}
if offline {
bail!(
"OCI image {image_ref:?} is not cached at {} and offline=true",
rootfs_dir.display()
);
}
fs::create_dir_all(&img_dir)?;
let mut token: Option<String> = None;
let base = format!("https://{}/v2/{}", parsed.registry, parsed.repository);
let manifest_url = format!("{base}/manifests/{}", parsed.reference);
let mut manifest: serde_json::Value = serde_json::from_reader(
oci_get(&manifest_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
)
.map_err(|e| format_err!("parse OCI manifest JSON: {e}"))?;
if let Some(manifests) = manifest.get("manifests").and_then(|v| v.as_array()) {
let chosen = manifests
.iter()
.find(|m| {
let plat = m.get("platform");
plat.and_then(|p| p.get("os")).and_then(|v| v.as_str()) == Some("linux")
&& plat
.and_then(|p| p.get("architecture"))
.and_then(|v| v.as_str())
== Some(arch)
})
.or_else(|| manifests.first())
.ok_or_else(|| format_err!("OCI index for {image_ref} has no manifests"))?;
let digest = chosen
.get("digest")
.and_then(|v| v.as_str())
.ok_or_else(|| format_err!("OCI index entry missing digest"))?;
let child_url = format!("{base}/manifests/{digest}");
manifest = serde_json::from_reader(
oci_get(&child_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
)
.map_err(|e| format_err!("parse child OCI manifest JSON: {e}"))?;
}
let mut img_cfg = OciImageConfig::default();
if let Some(cfg_digest) = manifest
.get("config")
.and_then(|c| c.get("digest"))
.and_then(|v| v.as_str())
{
let cfg_url = format!("{base}/blobs/{cfg_digest}");
if let Ok(resp) = oci_get(&cfg_url, None, &mut token)
&& let Ok(val) = serde_json::from_reader::<_, serde_json::Value>(resp.into_reader())
&& let Some(c) = val.get("config")
{
if let Some(envs) = c.get("Env").and_then(|v| v.as_array()) {
for e in envs.iter().filter_map(|v| v.as_str()) {
if let Some((k, v)) = e.split_once('=') {
img_cfg.env.insert(k.to_string(), v.to_string());
}
}
}
if let Some(wd) = c.get("WorkingDir").and_then(|v| v.as_str())
&& !wd.is_empty()
{
img_cfg.working_dir = Some(wd.to_string());
}
}
}
let layers = manifest
.get("layers")
.and_then(|v| v.as_array())
.ok_or_else(|| format_err!("OCI manifest for {image_ref} missing layers array"))?;
let tmp_rootfs = img_dir.join("rootfs.tmp");
if tmp_rootfs.exists() {
let _ = fs::remove_dir_all(&tmp_rootfs);
}
fs::create_dir_all(&tmp_rootfs)?;
for layer in layers {
let digest = layer
.get("digest")
.and_then(|v| v.as_str())
.ok_or_else(|| format_err!("OCI layer missing digest"))?;
let media_type = layer
.get("mediaType")
.and_then(|v| v.as_str())
.unwrap_or("");
let blob_url = format!("{base}/blobs/{digest}");
let resp = oci_get(&blob_url, None, &mut token)?;
let reader = resp.into_reader();
if media_type.contains("gzip") || media_type.ends_with("+gzip") || media_type.is_empty() {
unpack_layer_tar(GzDecoder::new(reader), &tmp_rootfs)?;
} else {
unpack_layer_tar(reader, &tmp_rootfs)?;
}
}
for d in ["proc", "dev", "sys", "tmp", "etc/ssl/certs"] {
let _ = fs::create_dir_all(tmp_rootfs.join(d));
}
if rootfs_dir.exists() {
let _ = fs::remove_dir_all(&rootfs_dir);
}
fs::rename(&tmp_rootfs, &rootfs_dir)?;
fs::write(&cfg_path, serde_json::to_vec_pretty(&img_cfg)?)?;
fs::write(&ready_marker, format!("{image_ref}\n"))?;
Ok(OciRootfs {
rootfs_dir,
config: img_cfg,
from_cache: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_docker_and_oci_image_refs() {
let a = parse_image_ref("alpine:3.21").unwrap();
assert_eq!(a.registry, "registry-1.docker.io");
assert_eq!(a.repository, "library/alpine");
assert_eq!(a.reference, "3.21");
let b = parse_image_ref("python").unwrap();
assert_eq!(b.registry, "registry-1.docker.io");
assert_eq!(b.repository, "library/python");
assert_eq!(b.reference, "latest");
let c = parse_image_ref("ghcr.io/njannasch/app:v1.2").unwrap();
assert_eq!(c.registry, "ghcr.io");
assert_eq!(c.repository, "njannasch/app");
assert_eq!(c.reference, "v1.2");
}
}