1use 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
46pub 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 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 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 #[cfg(unix)]
262 if let Ok(Some(link_target)) = entry.link_name() {
263 if dst.symlink_metadata().is_ok() {
264 let _ = fs::remove_file(&dst);
265 }
266 let _ = std::os::unix::fs::symlink(&link_target, &dst);
267 }
268 } else if etype.is_hard_link()
269 && let Ok(Some(link_target)) = entry.link_name()
270 && let Some(rel_target) = sanitize_rel_path(&link_target)
271 {
272 let src = rootfs.join(rel_target);
273 if src.exists() {
274 if dst.symlink_metadata().is_ok() {
275 let _ = fs::remove_file(&dst);
276 }
277 if fs::hard_link(&src, &dst).is_err() {
278 let _ = fs::copy(&src, &dst);
279 }
280 }
281 }
282 }
283 Ok(())
284}
285
286pub fn fetch_oci_rootfs(
288 image_ref: &str,
289 arch: &str,
290 cache_dir: &Path,
291 offline: bool,
292) -> Result<OciRootfs> {
293 let parsed = parse_image_ref(image_ref)?;
294 let mut hasher = Sha256::new();
295 hasher.update(
296 format!(
297 "{}/{}:{}@{}",
298 parsed.registry, parsed.repository, parsed.reference, arch
299 )
300 .as_bytes(),
301 );
302 let key = format!("{:x}", hasher.finalize());
303 let img_dir = cache_dir.join("oci").join(&key[..24]);
304 let rootfs_dir = img_dir.join("rootfs");
305 let ready_marker = img_dir.join(".ready");
306 let cfg_path = img_dir.join("config.json");
307
308 if ready_marker.exists() && rootfs_dir.is_dir() {
309 let config: OciImageConfig = fs::read_to_string(&cfg_path)
310 .ok()
311 .and_then(|s| serde_json::from_str(&s).ok())
312 .unwrap_or_default();
313 return Ok(OciRootfs {
314 rootfs_dir,
315 config,
316 from_cache: true,
317 });
318 }
319
320 if offline {
321 bail!(
322 "OCI image {image_ref:?} is not cached at {} and offline=true",
323 rootfs_dir.display()
324 );
325 }
326
327 fs::create_dir_all(&img_dir)?;
328 let mut token: Option<String> = None;
329 let base = format!("https://{}/v2/{}", parsed.registry, parsed.repository);
330
331 let manifest_url = format!("{base}/manifests/{}", parsed.reference);
333 let mut manifest: serde_json::Value = serde_json::from_reader(
334 oci_get(&manifest_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
335 )
336 .map_err(|e| format_err!("parse OCI manifest JSON: {e}"))?;
337
338 if let Some(manifests) = manifest.get("manifests").and_then(|v| v.as_array()) {
339 let chosen = manifests
340 .iter()
341 .find(|m| {
342 let plat = m.get("platform");
343 plat.and_then(|p| p.get("os")).and_then(|v| v.as_str()) == Some("linux")
344 && plat
345 .and_then(|p| p.get("architecture"))
346 .and_then(|v| v.as_str())
347 == Some(arch)
348 })
349 .or_else(|| manifests.first())
350 .ok_or_else(|| format_err!("OCI index for {image_ref} has no manifests"))?;
351 let digest = chosen
352 .get("digest")
353 .and_then(|v| v.as_str())
354 .ok_or_else(|| format_err!("OCI index entry missing digest"))?;
355 let child_url = format!("{base}/manifests/{digest}");
356 manifest = serde_json::from_reader(
357 oci_get(&child_url, Some(ACCEPT_MANIFEST), &mut token)?.into_reader(),
358 )
359 .map_err(|e| format_err!("parse child OCI manifest JSON: {e}"))?;
360 }
361
362 let mut img_cfg = OciImageConfig::default();
364 if let Some(cfg_digest) = manifest
365 .get("config")
366 .and_then(|c| c.get("digest"))
367 .and_then(|v| v.as_str())
368 {
369 let cfg_url = format!("{base}/blobs/{cfg_digest}");
370 if let Ok(resp) = oci_get(&cfg_url, None, &mut token)
371 && let Ok(val) = serde_json::from_reader::<_, serde_json::Value>(resp.into_reader())
372 && let Some(c) = val.get("config")
373 {
374 if let Some(envs) = c.get("Env").and_then(|v| v.as_array()) {
375 for e in envs.iter().filter_map(|v| v.as_str()) {
376 if let Some((k, v)) = e.split_once('=') {
377 img_cfg.env.insert(k.to_string(), v.to_string());
378 }
379 }
380 }
381 if let Some(wd) = c.get("WorkingDir").and_then(|v| v.as_str())
382 && !wd.is_empty()
383 {
384 img_cfg.working_dir = Some(wd.to_string());
385 }
386 }
387 }
388
389 let layers = manifest
391 .get("layers")
392 .and_then(|v| v.as_array())
393 .ok_or_else(|| format_err!("OCI manifest for {image_ref} missing layers array"))?;
394
395 let tmp_rootfs = img_dir.join("rootfs.tmp");
396 if tmp_rootfs.exists() {
397 let _ = fs::remove_dir_all(&tmp_rootfs);
398 }
399 fs::create_dir_all(&tmp_rootfs)?;
400
401 for layer in layers {
402 let digest = layer
403 .get("digest")
404 .and_then(|v| v.as_str())
405 .ok_or_else(|| format_err!("OCI layer missing digest"))?;
406 let media_type = layer
407 .get("mediaType")
408 .and_then(|v| v.as_str())
409 .unwrap_or("");
410 let blob_url = format!("{base}/blobs/{digest}");
411 let resp = oci_get(&blob_url, None, &mut token)?;
412 let reader = resp.into_reader();
413 if media_type.contains("gzip") || media_type.ends_with("+gzip") || media_type.is_empty() {
414 unpack_layer_tar(GzDecoder::new(reader), &tmp_rootfs)?;
415 } else {
416 unpack_layer_tar(reader, &tmp_rootfs)?;
417 }
418 }
419
420 for d in ["proc", "dev", "sys", "tmp", "etc/ssl/certs"] {
422 let _ = fs::create_dir_all(tmp_rootfs.join(d));
423 }
424
425 if rootfs_dir.exists() {
426 let _ = fs::remove_dir_all(&rootfs_dir);
427 }
428 fs::rename(&tmp_rootfs, &rootfs_dir)?;
429 fs::write(&cfg_path, serde_json::to_vec_pretty(&img_cfg)?)?;
430 fs::write(&ready_marker, format!("{image_ref}\n"))?;
431
432 Ok(OciRootfs {
433 rootfs_dir,
434 config: img_cfg,
435 from_cache: false,
436 })
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn parses_docker_and_oci_image_refs() {
445 let a = parse_image_ref("alpine:3.21").unwrap();
446 assert_eq!(a.registry, "registry-1.docker.io");
447 assert_eq!(a.repository, "library/alpine");
448 assert_eq!(a.reference, "3.21");
449
450 let b = parse_image_ref("python").unwrap();
451 assert_eq!(b.registry, "registry-1.docker.io");
452 assert_eq!(b.repository, "library/python");
453 assert_eq!(b.reference, "latest");
454
455 let c = parse_image_ref("ghcr.io/njannasch/app:v1.2").unwrap();
456 assert_eq!(c.registry, "ghcr.io");
457 assert_eq!(c.repository, "njannasch/app");
458 assert_eq!(c.reference, "v1.2");
459 }
460}