Skip to main content

krab_runtime/native/
registry.rs

1use super::oci::ImageConfig;
2use bytes::Bytes;
3use http_body_util::{BodyExt, Full};
4use hyper::body::Incoming;
5use hyper::{Request, Response, StatusCode};
6use hyper_util::rt::TokioIo;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::io;
10use std::path::Path;
11use std::sync::{Arc, OnceLock};
12use std::time::Duration;
13use tokio::io::AsyncWriteExt;
14
15pub const MAX_MANIFEST: u64 = 4 << 20;
16pub const MAX_CONFIG: u64 = 8 << 20;
17pub const MAX_LAYER: u64 = 2 << 30;
18const MAX_TOKEN: u64 = 256 << 10;
19const IO_TIMEOUT: Duration = Duration::from_secs(60);
20pub const PULL_DEADLINE: Duration = Duration::from_secs(600);
21
22const ACCEPT: &str = "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";
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct Reference {
26    pub registry: String,
27    pub repo: String,
28    pub reference: String,
29}
30
31fn bad(msg: impl Into<String>) -> io::Error {
32    io::Error::new(io::ErrorKind::InvalidData, msg.into())
33}
34
35pub fn digest_hex(d: &str) -> io::Result<&str> {
36    match d.strip_prefix("sha256:") {
37        Some(h) if h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) => {
38            Ok(h)
39        }
40        _ => Err(bad(format!("unsupported digest {d:?}"))),
41    }
42}
43
44pub fn sha256_hex(data: &[u8]) -> String {
45    hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
46}
47
48fn hex(b: &[u8]) -> String {
49    b.iter().map(|x| format!("{x:02x}")).collect()
50}
51
52pub fn parse_reference(image: &str) -> io::Result<Reference> {
53    if image.is_empty() || image.len() > 512 || image.bytes().any(|b| !b.is_ascii_graphic()) {
54        return Err(bad(format!("invalid image reference {image:?}")));
55    }
56    let (name, reference) = crate::docker::split_image(image);
57    let (registry, repo) = match name.split_once('/') {
58        Some((h, rest)) if h.contains('.') || h.contains(':') || h == "localhost" => {
59            (h.to_string(), rest.to_string())
60        }
61        _ => ("docker.io".to_string(), name.to_string()),
62    };
63    let registry = match registry.as_str() {
64        "docker.io" | "index.docker.io" => "registry-1.docker.io".to_string(),
65        _ => registry,
66    };
67    let repo = if registry == "registry-1.docker.io" && !repo.contains('/') {
68        format!("library/{repo}")
69    } else {
70        repo
71    };
72    let repo_ok = !repo.is_empty()
73        && repo.split('/').all(|c| {
74            !c.is_empty()
75                && c.bytes().all(|b| {
76                    b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
77                })
78                && c != "."
79                && c != ".."
80        });
81    let host_ok = registry
82        .bytes()
83        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':'));
84    let ref_ok = if reference.contains(':') {
85        digest_hex(reference).is_ok()
86    } else {
87        !reference.is_empty()
88            && reference.len() <= 128
89            && reference
90                .bytes()
91                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
92    };
93    if !repo_ok || !host_ok || !ref_ok {
94        return Err(bad(format!("invalid image reference {image:?}")));
95    }
96    Ok(Reference {
97        registry,
98        repo,
99        reference: reference.to_string(),
100    })
101}
102
103#[derive(Clone, Debug, Deserialize, PartialEq)]
104#[serde(rename_all = "camelCase")]
105pub struct Descriptor {
106    #[serde(default)]
107    pub media_type: String,
108    pub digest: String,
109    #[serde(default)]
110    pub size: u64,
111    #[serde(default)]
112    pub platform: Option<Platform>,
113}
114
115#[derive(Clone, Debug, Deserialize, PartialEq)]
116pub struct Platform {
117    #[serde(default)]
118    pub architecture: String,
119    #[serde(default)]
120    pub os: String,
121    #[serde(default)]
122    pub variant: Option<String>,
123}
124
125#[derive(Debug, PartialEq)]
126pub enum Manifest {
127    Index(Vec<Descriptor>),
128    Image {
129        config: Descriptor,
130        layers: Vec<Descriptor>,
131    },
132}
133
134pub fn parse_manifest(content_type: &str, body: &[u8]) -> io::Result<Manifest> {
135    let v: Value = serde_json::from_slice(body).map_err(|e| bad(format!("manifest: {e}")))?;
136    if v["schemaVersion"].as_i64() != Some(2) {
137        return Err(bad("only schemaVersion 2 manifests are supported"));
138    }
139    let mt = v["mediaType"]
140        .as_str()
141        .unwrap_or(content_type)
142        .split(';')
143        .next()
144        .unwrap_or_default()
145        .trim()
146        .to_string();
147    let index = mt.ends_with("manifest.list.v2+json")
148        || mt.ends_with("image.index.v1+json")
149        || (mt.is_empty() || mt == "application/json") && v["manifests"].is_array();
150    if index {
151        let m: Vec<Descriptor> = serde_json::from_value(v["manifests"].clone())
152            .map_err(|e| bad(format!("index: {e}")))?;
153        return Ok(Manifest::Index(m));
154    }
155    let image = mt.ends_with("distribution.manifest.v2+json")
156        || mt.ends_with("image.manifest.v1+json")
157        || (mt.is_empty() || mt == "application/json") && v["layers"].is_array();
158    if !image {
159        return Err(bad(format!("unsupported manifest type {mt:?}")));
160    }
161    let config: Descriptor =
162        serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("config: {e}")))?;
163    let layers: Vec<Descriptor> =
164        serde_json::from_value(v["layers"].clone()).map_err(|e| bad(format!("layers: {e}")))?;
165    digest_hex(&config.digest)?;
166    if layers.is_empty() || layers.len() > 127 {
167        return Err(bad("manifest has a bad number of layers"));
168    }
169    for l in &layers {
170        digest_hex(&l.digest)?;
171        if l.media_type.contains("zstd") || l.media_type.contains("foreign") {
172            return Err(bad(format!("unsupported layer type {}", l.media_type)));
173        }
174        if l.size > MAX_LAYER {
175            return Err(bad("layer too large"));
176        }
177    }
178    Ok(Manifest::Image { config, layers })
179}
180
181pub fn host_arch() -> &'static str {
182    match std::env::consts::ARCH {
183        "x86_64" => "amd64",
184        "aarch64" => "arm64",
185        "arm" => "arm",
186        other => other,
187    }
188}
189
190pub fn pick_platform<'a>(list: &'a [Descriptor], arch: &str) -> Option<&'a Descriptor> {
191    let matches = |d: &&Descriptor| {
192        d.platform
193            .as_ref()
194            .is_some_and(|p| p.os == "linux" && p.architecture == arch)
195    };
196    list.iter()
197        .filter(matches)
198        .find(|d| {
199            arch != "arm64"
200                || d.platform
201                    .as_ref()
202                    .and_then(|p| p.variant.as_deref())
203                    .is_none_or(|v| v == "v8")
204        })
205        .or_else(|| list.iter().find(matches))
206}
207
208pub fn parse_challenge(h: &str) -> Option<(String, Option<String>, Option<String>)> {
209    let rest = h
210        .trim()
211        .strip_prefix("Bearer ")
212        .or_else(|| h.trim().strip_prefix("bearer "))?;
213    let (mut realm, mut service, mut scope) = (None, None, None);
214    let mut s = rest.trim();
215    while !s.is_empty() {
216        let (k, after) = s.split_once('=')?;
217        let after = after.trim_start();
218        let (val, next) = if let Some(q) = after.strip_prefix('"') {
219            let end = q.find('"')?;
220            (&q[..end], &q[end + 1..])
221        } else {
222            let end = after.find(',').unwrap_or(after.len());
223            (&after[..end], &after[end..])
224        };
225        match k.trim().to_ascii_lowercase().as_str() {
226            "realm" => realm = Some(val.to_string()),
227            "service" => service = Some(val.to_string()),
228            "scope" => scope = Some(val.to_string()),
229            _ => {}
230        }
231        s = next.trim_start_matches([',', ' ']);
232    }
233    Some((realm?, service, scope))
234}
235
236fn enc(s: &str) -> String {
237    let mut out = String::with_capacity(s.len());
238    for b in s.bytes() {
239        if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
240            out.push(b as char);
241        } else {
242            out.push_str(&format!("%{b:02X}"));
243        }
244    }
245    out
246}
247
248#[derive(Clone, Debug, PartialEq)]
249struct Url {
250    host: String,
251    port: u16,
252    path: String,
253}
254
255fn parse_url(s: &str) -> io::Result<Url> {
256    let rest = s
257        .strip_prefix("https://")
258        .ok_or_else(|| bad(format!("only https URLs are allowed: {s}")))?;
259    let (auth, path) = match rest.find('/') {
260        Some(i) => (&rest[..i], &rest[i..]),
261        None => (rest, "/"),
262    };
263    if auth.contains('@') || auth.is_empty() {
264        return Err(bad("bad URL authority"));
265    }
266    let (host, port) = match auth.rsplit_once(':') {
267        Some((h, p)) => (h, p.parse().map_err(|_| bad("bad URL port"))?),
268        None => (auth, 443),
269    };
270    if host.is_empty()
271        || !host
272            .bytes()
273            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
274    {
275        return Err(bad("bad URL host"));
276    }
277    if path.bytes().any(|b| !b.is_ascii_graphic()) {
278        return Err(bad("bad URL path"));
279    }
280    Ok(Url {
281        host: host.to_string(),
282        port,
283        path: path.to_string(),
284    })
285}
286
287fn tls_config() -> io::Result<Arc<rustls::ClientConfig>> {
288    static CFG: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
289    if let Some(c) = CFG.get() {
290        return Ok(c.clone());
291    }
292    use rustls_pki_types::CertificateDer;
293    use rustls_pki_types::pem::PemObject;
294    let mut roots = rustls::RootCertStore::empty();
295    let mut files: Vec<String> = std::env::var("SSL_CERT_FILE").into_iter().collect();
296    files.extend(
297        [
298            "/etc/ssl/certs/ca-certificates.crt",
299            "/etc/pki/tls/certs/ca-bundle.crt",
300            "/etc/ssl/cert.pem",
301        ]
302        .map(String::from),
303    );
304    for f in files {
305        if let Ok(it) = CertificateDer::pem_file_iter(&f) {
306            for c in it.flatten() {
307                let _ = roots.add(c);
308            }
309        }
310        if !roots.is_empty() {
311            break;
312        }
313    }
314    if roots.is_empty() {
315        return Err(io::Error::other(
316            "no CA certificates found (set SSL_CERT_FILE)",
317        ));
318    }
319    let mut cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
320        rustls::crypto::ring::default_provider(),
321    ))
322    .with_safe_default_protocol_versions()
323    .map_err(io::Error::other)?
324    .with_root_certificates(roots)
325    .with_no_client_auth();
326    cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
327    let cfg = Arc::new(cfg);
328    let _ = CFG.set(cfg.clone());
329    Ok(cfg)
330}
331
332async fn send(url: &Url, headers: &[(&str, String)]) -> io::Result<Response<Incoming>> {
333    let cfg = tls_config()?;
334    let fut = async {
335        let tcp = tokio::net::TcpStream::connect((url.host.as_str(), url.port)).await?;
336        let name = rustls_pki_types::ServerName::try_from(url.host.clone())
337            .map_err(|_| bad("bad TLS server name"))?;
338        let tls = tokio_rustls::TlsConnector::from(cfg)
339            .connect(name, tcp)
340            .await?;
341        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
342            .await
343            .map_err(io::Error::other)?;
344        tokio::spawn(async move {
345            let _ = conn.await;
346        });
347        let mut req = Request::get(url.path.as_str())
348            .header("Host", url.host.as_str())
349            .header("User-Agent", "krab/0.1");
350        for (k, v) in headers {
351            req = req.header(*k, v.as_str());
352        }
353        let req = req
354            .body(Full::new(Bytes::new()))
355            .map_err(io::Error::other)?;
356        sender.send_request(req).await.map_err(io::Error::other)
357    };
358    tokio::time::timeout(IO_TIMEOUT, fut)
359        .await
360        .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry request timed out"))?
361}
362
363async fn get(
364    url: &str,
365    token: Option<&str>,
366    accept: Option<&str>,
367) -> io::Result<Response<Incoming>> {
368    let mut cur = parse_url(url)?;
369    let origin = cur.host.clone();
370    for _ in 0..6 {
371        let mut h: Vec<(&str, String)> = Vec::new();
372        if let Some(a) = accept {
373            h.push(("Accept", a.to_string()));
374        }
375        if let Some(t) = token.filter(|_| cur.host == origin) {
376            h.push(("Authorization", format!("Bearer {t}")));
377        }
378        let resp = send(&cur, &h).await?;
379        if !resp.status().is_redirection() {
380            return Ok(resp);
381        }
382        let loc = resp
383            .headers()
384            .get("location")
385            .and_then(|v| v.to_str().ok())
386            .ok_or_else(|| bad("redirect without location"))?
387            .to_string();
388        cur = if loc.starts_with('/') {
389            Url { path: loc, ..cur }
390        } else {
391            parse_url(&loc)?
392        };
393    }
394    Err(bad("too many redirects"))
395}
396
397async fn read_limited(resp: Response<Incoming>, max: u64) -> io::Result<Vec<u8>> {
398    if let Some(n) = content_length(&resp)
399        && n > max
400    {
401        return Err(bad("response too large"));
402    }
403    let mut body = resp.into_body();
404    let mut out = Vec::new();
405    loop {
406        let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
407            .await
408            .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry read timed out"))?;
409        let Some(frame) = frame else { break };
410        if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
411            if out.len() as u64 + d.len() as u64 > max {
412                return Err(bad("response too large"));
413            }
414            out.extend_from_slice(&d);
415        }
416    }
417    Ok(out)
418}
419
420fn content_length(resp: &Response<Incoming>) -> Option<u64> {
421    resp.headers()
422        .get("content-length")
423        .and_then(|v| v.to_str().ok())
424        .and_then(|v| v.parse().ok())
425}
426
427fn status_err(what: &str, s: StatusCode) -> io::Error {
428    let kind = match s {
429        StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
430        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => io::ErrorKind::PermissionDenied,
431        _ => io::ErrorKind::Other,
432    };
433    io::Error::new(kind, format!("{what}: registry returned {s}"))
434}
435
436pub struct Session {
437    pub r: Reference,
438    token: Option<String>,
439}
440
441impl Session {
442    pub fn new(r: Reference) -> Self {
443        Self { r, token: None }
444    }
445
446    fn url(&self, kind: &str, reference: &str) -> String {
447        format!(
448            "https://{}/v2/{}/{kind}/{reference}",
449            self.r.registry, self.r.repo
450        )
451    }
452
453    async fn authorize(&mut self, challenge: &str) -> io::Result<()> {
454        let (realm, service, scope) =
455            parse_challenge(challenge).ok_or_else(|| bad("unsupported registry auth challenge"))?;
456        let scope = scope.unwrap_or_else(|| format!("repository:{}:pull", self.r.repo));
457        let mut url = realm.clone();
458        url.push(if realm.contains('?') { '&' } else { '?' });
459        if let Some(s) = service {
460            url.push_str(&format!("service={}&", enc(&s)));
461        }
462        url.push_str(&format!("scope={}", enc(&scope)));
463        let resp = get(&url, None, None).await?;
464        if !resp.status().is_success() {
465            return Err(status_err("token", resp.status()));
466        }
467        let body = read_limited(resp, MAX_TOKEN).await?;
468        let v: Value = serde_json::from_slice(&body).map_err(|_| bad("bad token response"))?;
469        let t = v["token"]
470            .as_str()
471            .or_else(|| v["access_token"].as_str())
472            .filter(|t| !t.is_empty())
473            .ok_or_else(|| bad("token response without token"))?;
474        self.token = Some(t.to_string());
475        Ok(())
476    }
477
478    async fn fetch(&mut self, url: &str, accept: Option<&str>) -> io::Result<Response<Incoming>> {
479        let mut retried = false;
480        loop {
481            let resp = get(url, self.token.as_deref(), accept).await?;
482            if resp.status() == StatusCode::UNAUTHORIZED && !retried {
483                let ch = resp
484                    .headers()
485                    .get("www-authenticate")
486                    .and_then(|v| v.to_str().ok())
487                    .unwrap_or_default()
488                    .to_string();
489                self.authorize(&ch).await?;
490                retried = true;
491                continue;
492            }
493            if !resp.status().is_success() {
494                return Err(status_err(url, resp.status()));
495            }
496            return Ok(resp);
497        }
498    }
499
500    pub async fn manifest(&mut self, reference: &str) -> io::Result<(String, Manifest)> {
501        let url = self.url("manifests", reference);
502        let resp = self.fetch(&url, Some(ACCEPT)).await?;
503        let ct = resp
504            .headers()
505            .get("content-type")
506            .and_then(|v| v.to_str().ok())
507            .unwrap_or_default()
508            .to_string();
509        let body = read_limited(resp, MAX_MANIFEST).await?;
510        let digest = format!("sha256:{}", sha256_hex(&body));
511        if reference.starts_with("sha256:") && digest != reference {
512            return Err(bad(format!("manifest digest mismatch for {reference}")));
513        }
514        Ok((digest, parse_manifest(&ct, &body)?))
515    }
516
517    pub async fn blob_bytes(&mut self, digest: &str, max: u64) -> io::Result<Vec<u8>> {
518        digest_hex(digest)?;
519        let resp = self.fetch(&self.url("blobs", digest), None).await?;
520        let body = read_limited(resp, max).await?;
521        if format!("sha256:{}", sha256_hex(&body)) != digest {
522            return Err(bad(format!("blob digest mismatch for {digest}")));
523        }
524        Ok(body)
525    }
526
527    pub async fn blob_to_file(&mut self, digest: &str, dst: &Path, max: u64) -> io::Result<()> {
528        let hex_want = digest_hex(digest)?.to_string();
529        if tokio::fs::metadata(dst).await.is_ok() {
530            return Ok(());
531        }
532        let resp = self.fetch(&self.url("blobs", digest), None).await?;
533        if content_length(&resp).is_some_and(|n| n > max) {
534            return Err(bad("layer too large"));
535        }
536        let tmp = dst.with_extension(format!("tmp{}", std::process::id()));
537        let mut f = tokio::fs::File::create(&tmp).await?;
538        let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
539        let mut total = 0u64;
540        let mut body = resp.into_body();
541        let res: io::Result<()> = async {
542            loop {
543                let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
544                    .await
545                    .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "blob read timed out"))?;
546                let Some(frame) = frame else { break };
547                if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
548                    total += d.len() as u64;
549                    if total > max {
550                        return Err(bad("layer too large"));
551                    }
552                    ctx.update(&d);
553                    f.write_all(&d).await?;
554                }
555            }
556            f.flush().await?;
557            f.sync_all().await?;
558            if hex(ctx.finish().as_ref()) != hex_want {
559                return Err(bad(format!("blob digest mismatch for {digest}")));
560            }
561            Ok(())
562        }
563        .await;
564        if let Err(e) = res {
565            let _ = tokio::fs::remove_file(&tmp).await;
566            return Err(e);
567        }
568        tokio::fs::rename(&tmp, dst).await
569    }
570}
571
572#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
573pub struct ImageRecord {
574    pub image: String,
575    pub digest: String,
576    pub config_digest: String,
577    pub layers: Vec<String>,
578    pub config: ImageConfig,
579}
580
581pub fn image_config(blob: &[u8]) -> io::Result<ImageConfig> {
582    let v: Value = serde_json::from_slice(blob).map_err(|e| bad(format!("image config: {e}")))?;
583    let os = v["os"].as_str().unwrap_or("linux");
584    if os != "linux" {
585        return Err(bad(format!("image os {os} is not supported")));
586    }
587    if v["config"].is_null() {
588        return Ok(ImageConfig::default());
589    }
590    serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("image config: {e}")))
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use serde_json::json;
597
598    #[test]
599    fn references() {
600        let r = parse_reference("nginx:alpine").unwrap();
601        assert_eq!(
602            r,
603            Reference {
604                registry: "registry-1.docker.io".into(),
605                repo: "library/nginx".into(),
606                reference: "alpine".into()
607            }
608        );
609        let r = parse_reference("ghcr.io/org/app@sha256:".to_string().as_str());
610        assert!(r.is_err());
611        let d = format!("sha256:{}", "a".repeat(64));
612        let r = parse_reference(&format!("ghcr.io/org/app@{d}")).unwrap();
613        assert_eq!(
614            (r.registry.as_str(), r.repo.as_str()),
615            ("ghcr.io", "org/app")
616        );
617        assert_eq!(r.reference, d);
618        let r = parse_reference("localhost:5000/x").unwrap();
619        assert_eq!(
620            (r.registry.as_str(), r.reference.as_str()),
621            ("localhost:5000", "latest")
622        );
623        assert_eq!(
624            parse_reference("bitnami/redis").unwrap().repo,
625            "bitnami/redis"
626        );
627        for bad in ["", "UPPER/x", "a/../b", "x:t@g", "a b", "quay.io/a//b"] {
628            assert!(parse_reference(bad).is_err(), "{bad}");
629        }
630    }
631
632    #[test]
633    fn manifest_list_picks_platform() {
634        let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
635        let body = json!({
636            "schemaVersion": 2,
637            "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
638            "manifests": [
639                {"digest": d('a'), "mediaType": "x", "size": 1, "platform": {"architecture": "arm", "os": "linux", "variant": "v7"}},
640                {"digest": d('b'), "size": 1, "platform": {"architecture": "arm64", "os": "linux", "variant": "v8"}},
641                {"digest": d('c'), "size": 1, "platform": {"architecture": "amd64", "os": "linux"}},
642                {"digest": d('d'), "size": 1, "platform": {"architecture": "unknown", "os": "unknown"}}
643            ]
644        });
645        let Manifest::Index(list) = parse_manifest("", body.to_string().as_bytes()).unwrap() else {
646            panic!()
647        };
648        assert_eq!(pick_platform(&list, "amd64").unwrap().digest, d('c'));
649        assert_eq!(pick_platform(&list, "arm64").unwrap().digest, d('b'));
650        assert!(pick_platform(&list, "s390x").is_none());
651        let oci = json!({"schemaVersion": 2, "manifests": [{"digest": d('e'), "platform": {"architecture": "amd64", "os": "linux"}}]});
652        assert!(matches!(
653            parse_manifest(
654                "application/vnd.oci.image.index.v1+json",
655                oci.to_string().as_bytes()
656            )
657            .unwrap(),
658            Manifest::Index(_)
659        ));
660    }
661
662    #[test]
663    fn image_manifests() {
664        let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
665        let docker = json!({
666            "schemaVersion": 2,
667            "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
668            "config": {"mediaType": "application/vnd.docker.container.image.v1+json", "digest": d('1'), "size": 10},
669            "layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "digest": d('2'), "size": 100}]
670        });
671        let Manifest::Image { config, layers } =
672            parse_manifest("", docker.to_string().as_bytes()).unwrap()
673        else {
674            panic!()
675        };
676        assert_eq!(config.digest, d('1'));
677        assert_eq!(layers[0].digest, d('2'));
678        let oci = json!({
679            "schemaVersion": 2,
680            "config": {"digest": d('3')},
681            "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": d('4')}]
682        });
683        assert!(matches!(
684            parse_manifest(
685                "application/vnd.oci.image.manifest.v1+json",
686                oci.to_string().as_bytes()
687            )
688            .unwrap(),
689            Manifest::Image { .. }
690        ));
691        let zstd = json!({"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": d('3')}, "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar+zstd", "digest": d('4')}]});
692        assert!(parse_manifest("", zstd.to_string().as_bytes()).is_err());
693        let evil = json!({"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": "sha256:../../x"}, "layers": [{"digest": d('4')}]});
694        assert!(parse_manifest("", evil.to_string().as_bytes()).is_err());
695        assert!(parse_manifest("", br#"{"schemaVersion": 1}"#).is_err());
696    }
697
698    #[test]
699    fn challenges_and_urls() {
700        let (realm, service, scope) = parse_challenge(
701            r#"Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/nginx:pull""#,
702        )
703        .unwrap();
704        assert_eq!(realm, "https://auth.docker.io/token");
705        assert_eq!(service.as_deref(), Some("registry.docker.io"));
706        assert_eq!(scope.as_deref(), Some("repository:library/nginx:pull"));
707        let (realm, service, _) =
708            parse_challenge(r#"Bearer realm="https://ghcr.io/token",service="ghcr.io""#).unwrap();
709        assert_eq!(
710            (realm.as_str(), service.as_deref()),
711            ("https://ghcr.io/token", Some("ghcr.io"))
712        );
713        assert!(parse_challenge("Basic realm=x").is_none());
714        let u = parse_url("https://r.io:5000/v2/x?y=1").unwrap();
715        assert_eq!(
716            (u.host.as_str(), u.port, u.path.as_str()),
717            ("r.io", 5000, "/v2/x?y=1")
718        );
719        assert!(parse_url("http://r.io/").is_err());
720        assert!(parse_url("https://user@r.io/").is_err());
721        assert!(digest_hex("sha256:ABC").is_err());
722    }
723
724    #[test]
725    fn image_config_parse() {
726        let c = image_config(br#"{"os":"linux","config":{"Cmd":["sh"],"Env":["A=1"],"User":"1"}}"#)
727            .unwrap();
728        assert_eq!(c.cmd, Some(vec!["sh".to_string()]));
729        assert!(image_config(br#"{"os":"windows","config":{}}"#).is_err());
730    }
731}