krab-runtime 0.2.0

Container runtime abstraction and Docker backend for krabkube
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use super::oci::ImageConfig;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::io::AsyncWriteExt;

pub const MAX_MANIFEST: u64 = 4 << 20;
pub const MAX_CONFIG: u64 = 8 << 20;
pub const MAX_LAYER: u64 = 2 << 30;
const MAX_TOKEN: u64 = 256 << 10;
const IO_TIMEOUT: Duration = Duration::from_secs(60);
pub const PULL_DEADLINE: Duration = Duration::from_secs(600);

const 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";

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reference {
    pub registry: String,
    pub repo: String,
    pub reference: String,
}

fn bad(msg: impl Into<String>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, msg.into())
}

pub fn digest_hex(d: &str) -> io::Result<&str> {
    match d.strip_prefix("sha256:") {
        Some(h) if h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) => {
            Ok(h)
        }
        _ => Err(bad(format!("unsupported digest {d:?}"))),
    }
}

pub fn sha256_hex(data: &[u8]) -> String {
    hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

pub fn parse_reference(image: &str) -> io::Result<Reference> {
    if image.is_empty() || image.len() > 512 || image.bytes().any(|b| !b.is_ascii_graphic()) {
        return Err(bad(format!("invalid image reference {image:?}")));
    }
    let (name, reference) = crate::docker::split_image(image);
    let (registry, repo) = match name.split_once('/') {
        Some((h, rest)) if h.contains('.') || h.contains(':') || h == "localhost" => {
            (h.to_string(), rest.to_string())
        }
        _ => ("docker.io".to_string(), name.to_string()),
    };
    let registry = match registry.as_str() {
        "docker.io" | "index.docker.io" => "registry-1.docker.io".to_string(),
        _ => registry,
    };
    let repo = if registry == "registry-1.docker.io" && !repo.contains('/') {
        format!("library/{repo}")
    } else {
        repo
    };
    let repo_ok = !repo.is_empty()
        && repo.split('/').all(|c| {
            !c.is_empty()
                && c.bytes().all(|b| {
                    b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
                })
                && c != "."
                && c != ".."
        });
    let host_ok = registry
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':'));
    let ref_ok = if reference.contains(':') {
        digest_hex(reference).is_ok()
    } else {
        !reference.is_empty()
            && reference.len() <= 128
            && reference
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
    };
    if !repo_ok || !host_ok || !ref_ok {
        return Err(bad(format!("invalid image reference {image:?}")));
    }
    Ok(Reference {
        registry,
        repo,
        reference: reference.to_string(),
    })
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Descriptor {
    #[serde(default)]
    pub media_type: String,
    pub digest: String,
    #[serde(default)]
    pub size: u64,
    #[serde(default)]
    pub platform: Option<Platform>,
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Platform {
    #[serde(default)]
    pub architecture: String,
    #[serde(default)]
    pub os: String,
    #[serde(default)]
    pub variant: Option<String>,
}

#[derive(Debug, PartialEq)]
pub enum Manifest {
    Index(Vec<Descriptor>),
    Image {
        config: Descriptor,
        layers: Vec<Descriptor>,
    },
}

pub fn parse_manifest(content_type: &str, body: &[u8]) -> io::Result<Manifest> {
    let v: Value = serde_json::from_slice(body).map_err(|e| bad(format!("manifest: {e}")))?;
    if v["schemaVersion"].as_i64() != Some(2) {
        return Err(bad("only schemaVersion 2 manifests are supported"));
    }
    let mt = v["mediaType"]
        .as_str()
        .unwrap_or(content_type)
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_string();
    let index = mt.ends_with("manifest.list.v2+json")
        || mt.ends_with("image.index.v1+json")
        || (mt.is_empty() || mt == "application/json") && v["manifests"].is_array();
    if index {
        let m: Vec<Descriptor> = serde_json::from_value(v["manifests"].clone())
            .map_err(|e| bad(format!("index: {e}")))?;
        return Ok(Manifest::Index(m));
    }
    let image = mt.ends_with("distribution.manifest.v2+json")
        || mt.ends_with("image.manifest.v1+json")
        || (mt.is_empty() || mt == "application/json") && v["layers"].is_array();
    if !image {
        return Err(bad(format!("unsupported manifest type {mt:?}")));
    }
    let config: Descriptor =
        serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("config: {e}")))?;
    let layers: Vec<Descriptor> =
        serde_json::from_value(v["layers"].clone()).map_err(|e| bad(format!("layers: {e}")))?;
    digest_hex(&config.digest)?;
    if layers.is_empty() || layers.len() > 127 {
        return Err(bad("manifest has a bad number of layers"));
    }
    for l in &layers {
        digest_hex(&l.digest)?;
        if l.media_type.contains("zstd") || l.media_type.contains("foreign") {
            return Err(bad(format!("unsupported layer type {}", l.media_type)));
        }
        if l.size > MAX_LAYER {
            return Err(bad("layer too large"));
        }
    }
    Ok(Manifest::Image { config, layers })
}

pub fn host_arch() -> &'static str {
    match std::env::consts::ARCH {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        "arm" => "arm",
        other => other,
    }
}

pub fn pick_platform<'a>(list: &'a [Descriptor], arch: &str) -> Option<&'a Descriptor> {
    let matches = |d: &&Descriptor| {
        d.platform
            .as_ref()
            .is_some_and(|p| p.os == "linux" && p.architecture == arch)
    };
    list.iter()
        .filter(matches)
        .find(|d| {
            arch != "arm64"
                || d.platform
                    .as_ref()
                    .and_then(|p| p.variant.as_deref())
                    .is_none_or(|v| v == "v8")
        })
        .or_else(|| list.iter().find(matches))
}

pub fn parse_challenge(h: &str) -> Option<(String, Option<String>, Option<String>)> {
    let rest = h
        .trim()
        .strip_prefix("Bearer ")
        .or_else(|| h.trim().strip_prefix("bearer "))?;
    let (mut realm, mut service, mut scope) = (None, None, None);
    let mut s = rest.trim();
    while !s.is_empty() {
        let (k, after) = s.split_once('=')?;
        let after = after.trim_start();
        let (val, next) = if let Some(q) = after.strip_prefix('"') {
            let end = q.find('"')?;
            (&q[..end], &q[end + 1..])
        } else {
            let end = after.find(',').unwrap_or(after.len());
            (&after[..end], &after[end..])
        };
        match k.trim().to_ascii_lowercase().as_str() {
            "realm" => realm = Some(val.to_string()),
            "service" => service = Some(val.to_string()),
            "scope" => scope = Some(val.to_string()),
            _ => {}
        }
        s = next.trim_start_matches([',', ' ']);
    }
    Some((realm?, service, scope))
}

fn enc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

#[derive(Clone, Debug, PartialEq)]
struct Url {
    host: String,
    port: u16,
    path: String,
}

fn parse_url(s: &str) -> io::Result<Url> {
    let rest = s
        .strip_prefix("https://")
        .ok_or_else(|| bad(format!("only https URLs are allowed: {s}")))?;
    let (auth, path) = match rest.find('/') {
        Some(i) => (&rest[..i], &rest[i..]),
        None => (rest, "/"),
    };
    if auth.contains('@') || auth.is_empty() {
        return Err(bad("bad URL authority"));
    }
    let (host, port) = match auth.rsplit_once(':') {
        Some((h, p)) => (h, p.parse().map_err(|_| bad("bad URL port"))?),
        None => (auth, 443),
    };
    if host.is_empty()
        || !host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
    {
        return Err(bad("bad URL host"));
    }
    if path.bytes().any(|b| !b.is_ascii_graphic()) {
        return Err(bad("bad URL path"));
    }
    Ok(Url {
        host: host.to_string(),
        port,
        path: path.to_string(),
    })
}

fn tls_config() -> io::Result<Arc<rustls::ClientConfig>> {
    static CFG: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
    if let Some(c) = CFG.get() {
        return Ok(c.clone());
    }
    use rustls_pki_types::CertificateDer;
    use rustls_pki_types::pem::PemObject;
    let mut roots = rustls::RootCertStore::empty();
    let mut files: Vec<String> = std::env::var("SSL_CERT_FILE").into_iter().collect();
    files.extend(
        [
            "/etc/ssl/certs/ca-certificates.crt",
            "/etc/pki/tls/certs/ca-bundle.crt",
            "/etc/ssl/cert.pem",
        ]
        .map(String::from),
    );
    for f in files {
        if let Ok(it) = CertificateDer::pem_file_iter(&f) {
            for c in it.flatten() {
                let _ = roots.add(c);
            }
        }
        if !roots.is_empty() {
            break;
        }
    }
    if roots.is_empty() {
        return Err(io::Error::other(
            "no CA certificates found (set SSL_CERT_FILE)",
        ));
    }
    let mut cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
        rustls::crypto::ring::default_provider(),
    ))
    .with_safe_default_protocol_versions()
    .map_err(io::Error::other)?
    .with_root_certificates(roots)
    .with_no_client_auth();
    cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
    let cfg = Arc::new(cfg);
    let _ = CFG.set(cfg.clone());
    Ok(cfg)
}

async fn send(url: &Url, headers: &[(&str, String)]) -> io::Result<Response<Incoming>> {
    let cfg = tls_config()?;
    let fut = async {
        let tcp = tokio::net::TcpStream::connect((url.host.as_str(), url.port)).await?;
        let name = rustls_pki_types::ServerName::try_from(url.host.clone())
            .map_err(|_| bad("bad TLS server name"))?;
        let tls = tokio_rustls::TlsConnector::from(cfg)
            .connect(name, tcp)
            .await?;
        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
            .await
            .map_err(io::Error::other)?;
        tokio::spawn(async move {
            let _ = conn.await;
        });
        let mut req = Request::get(url.path.as_str())
            .header("Host", url.host.as_str())
            .header("User-Agent", "krab/0.1");
        for (k, v) in headers {
            req = req.header(*k, v.as_str());
        }
        let req = req
            .body(Full::new(Bytes::new()))
            .map_err(io::Error::other)?;
        sender.send_request(req).await.map_err(io::Error::other)
    };
    tokio::time::timeout(IO_TIMEOUT, fut)
        .await
        .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry request timed out"))?
}

async fn get(
    url: &str,
    token: Option<&str>,
    accept: Option<&str>,
) -> io::Result<Response<Incoming>> {
    let mut cur = parse_url(url)?;
    let origin = cur.host.clone();
    for _ in 0..6 {
        let mut h: Vec<(&str, String)> = Vec::new();
        if let Some(a) = accept {
            h.push(("Accept", a.to_string()));
        }
        if let Some(t) = token.filter(|_| cur.host == origin) {
            h.push(("Authorization", format!("Bearer {t}")));
        }
        let resp = send(&cur, &h).await?;
        if !resp.status().is_redirection() {
            return Ok(resp);
        }
        let loc = resp
            .headers()
            .get("location")
            .and_then(|v| v.to_str().ok())
            .ok_or_else(|| bad("redirect without location"))?
            .to_string();
        cur = if loc.starts_with('/') {
            Url { path: loc, ..cur }
        } else {
            parse_url(&loc)?
        };
    }
    Err(bad("too many redirects"))
}

async fn read_limited(resp: Response<Incoming>, max: u64) -> io::Result<Vec<u8>> {
    if let Some(n) = content_length(&resp)
        && n > max
    {
        return Err(bad("response too large"));
    }
    let mut body = resp.into_body();
    let mut out = Vec::new();
    loop {
        let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
            .await
            .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry read timed out"))?;
        let Some(frame) = frame else { break };
        if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
            if out.len() as u64 + d.len() as u64 > max {
                return Err(bad("response too large"));
            }
            out.extend_from_slice(&d);
        }
    }
    Ok(out)
}

fn content_length(resp: &Response<Incoming>) -> Option<u64> {
    resp.headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse().ok())
}

fn status_err(what: &str, s: StatusCode) -> io::Error {
    let kind = match s {
        StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => io::ErrorKind::PermissionDenied,
        _ => io::ErrorKind::Other,
    };
    io::Error::new(kind, format!("{what}: registry returned {s}"))
}

pub struct Session {
    pub r: Reference,
    token: Option<String>,
}

impl Session {
    pub fn new(r: Reference) -> Self {
        Self { r, token: None }
    }

    fn url(&self, kind: &str, reference: &str) -> String {
        format!(
            "https://{}/v2/{}/{kind}/{reference}",
            self.r.registry, self.r.repo
        )
    }

    async fn authorize(&mut self, challenge: &str) -> io::Result<()> {
        let (realm, service, scope) =
            parse_challenge(challenge).ok_or_else(|| bad("unsupported registry auth challenge"))?;
        let scope = scope.unwrap_or_else(|| format!("repository:{}:pull", self.r.repo));
        let mut url = realm.clone();
        url.push(if realm.contains('?') { '&' } else { '?' });
        if let Some(s) = service {
            url.push_str(&format!("service={}&", enc(&s)));
        }
        url.push_str(&format!("scope={}", enc(&scope)));
        let resp = get(&url, None, None).await?;
        if !resp.status().is_success() {
            return Err(status_err("token", resp.status()));
        }
        let body = read_limited(resp, MAX_TOKEN).await?;
        let v: Value = serde_json::from_slice(&body).map_err(|_| bad("bad token response"))?;
        let t = v["token"]
            .as_str()
            .or_else(|| v["access_token"].as_str())
            .filter(|t| !t.is_empty())
            .ok_or_else(|| bad("token response without token"))?;
        self.token = Some(t.to_string());
        Ok(())
    }

    async fn fetch(&mut self, url: &str, accept: Option<&str>) -> io::Result<Response<Incoming>> {
        let mut retried = false;
        loop {
            let resp = get(url, self.token.as_deref(), accept).await?;
            if resp.status() == StatusCode::UNAUTHORIZED && !retried {
                let ch = resp
                    .headers()
                    .get("www-authenticate")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or_default()
                    .to_string();
                self.authorize(&ch).await?;
                retried = true;
                continue;
            }
            if !resp.status().is_success() {
                return Err(status_err(url, resp.status()));
            }
            return Ok(resp);
        }
    }

    pub async fn manifest(&mut self, reference: &str) -> io::Result<(String, Manifest)> {
        let url = self.url("manifests", reference);
        let resp = self.fetch(&url, Some(ACCEPT)).await?;
        let ct = resp
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string();
        let body = read_limited(resp, MAX_MANIFEST).await?;
        let digest = format!("sha256:{}", sha256_hex(&body));
        if reference.starts_with("sha256:") && digest != reference {
            return Err(bad(format!("manifest digest mismatch for {reference}")));
        }
        Ok((digest, parse_manifest(&ct, &body)?))
    }

    pub async fn blob_bytes(&mut self, digest: &str, max: u64) -> io::Result<Vec<u8>> {
        digest_hex(digest)?;
        let resp = self.fetch(&self.url("blobs", digest), None).await?;
        let body = read_limited(resp, max).await?;
        if format!("sha256:{}", sha256_hex(&body)) != digest {
            return Err(bad(format!("blob digest mismatch for {digest}")));
        }
        Ok(body)
    }

    pub async fn blob_to_file(&mut self, digest: &str, dst: &Path, max: u64) -> io::Result<()> {
        let hex_want = digest_hex(digest)?.to_string();
        if tokio::fs::metadata(dst).await.is_ok() {
            return Ok(());
        }
        let resp = self.fetch(&self.url("blobs", digest), None).await?;
        if content_length(&resp).is_some_and(|n| n > max) {
            return Err(bad("layer too large"));
        }
        let tmp = dst.with_extension(format!("tmp{}", std::process::id()));
        let mut f = tokio::fs::File::create(&tmp).await?;
        let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
        let mut total = 0u64;
        let mut body = resp.into_body();
        let res: io::Result<()> = async {
            loop {
                let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
                    .await
                    .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "blob read timed out"))?;
                let Some(frame) = frame else { break };
                if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
                    total += d.len() as u64;
                    if total > max {
                        return Err(bad("layer too large"));
                    }
                    ctx.update(&d);
                    f.write_all(&d).await?;
                }
            }
            f.flush().await?;
            f.sync_all().await?;
            if hex(ctx.finish().as_ref()) != hex_want {
                return Err(bad(format!("blob digest mismatch for {digest}")));
            }
            Ok(())
        }
        .await;
        if let Err(e) = res {
            let _ = tokio::fs::remove_file(&tmp).await;
            return Err(e);
        }
        tokio::fs::rename(&tmp, dst).await
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct ImageRecord {
    pub image: String,
    pub digest: String,
    pub config_digest: String,
    pub layers: Vec<String>,
    pub config: ImageConfig,
}

pub fn image_config(blob: &[u8]) -> io::Result<ImageConfig> {
    let v: Value = serde_json::from_slice(blob).map_err(|e| bad(format!("image config: {e}")))?;
    let os = v["os"].as_str().unwrap_or("linux");
    if os != "linux" {
        return Err(bad(format!("image os {os} is not supported")));
    }
    if v["config"].is_null() {
        return Ok(ImageConfig::default());
    }
    serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("image config: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn references() {
        let r = parse_reference("nginx:alpine").unwrap();
        assert_eq!(
            r,
            Reference {
                registry: "registry-1.docker.io".into(),
                repo: "library/nginx".into(),
                reference: "alpine".into()
            }
        );
        let r = parse_reference("ghcr.io/org/app@sha256:".to_string().as_str());
        assert!(r.is_err());
        let d = format!("sha256:{}", "a".repeat(64));
        let r = parse_reference(&format!("ghcr.io/org/app@{d}")).unwrap();
        assert_eq!(
            (r.registry.as_str(), r.repo.as_str()),
            ("ghcr.io", "org/app")
        );
        assert_eq!(r.reference, d);
        let r = parse_reference("localhost:5000/x").unwrap();
        assert_eq!(
            (r.registry.as_str(), r.reference.as_str()),
            ("localhost:5000", "latest")
        );
        assert_eq!(
            parse_reference("bitnami/redis").unwrap().repo,
            "bitnami/redis"
        );
        for bad in ["", "UPPER/x", "a/../b", "x:t@g", "a b", "quay.io/a//b"] {
            assert!(parse_reference(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn manifest_list_picks_platform() {
        let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
        let body = json!({
            "schemaVersion": 2,
            "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
            "manifests": [
                {"digest": d('a'), "mediaType": "x", "size": 1, "platform": {"architecture": "arm", "os": "linux", "variant": "v7"}},
                {"digest": d('b'), "size": 1, "platform": {"architecture": "arm64", "os": "linux", "variant": "v8"}},
                {"digest": d('c'), "size": 1, "platform": {"architecture": "amd64", "os": "linux"}},
                {"digest": d('d'), "size": 1, "platform": {"architecture": "unknown", "os": "unknown"}}
            ]
        });
        let Manifest::Index(list) = parse_manifest("", body.to_string().as_bytes()).unwrap() else {
            panic!()
        };
        assert_eq!(pick_platform(&list, "amd64").unwrap().digest, d('c'));
        assert_eq!(pick_platform(&list, "arm64").unwrap().digest, d('b'));
        assert!(pick_platform(&list, "s390x").is_none());
        let oci = json!({"schemaVersion": 2, "manifests": [{"digest": d('e'), "platform": {"architecture": "amd64", "os": "linux"}}]});
        assert!(matches!(
            parse_manifest(
                "application/vnd.oci.image.index.v1+json",
                oci.to_string().as_bytes()
            )
            .unwrap(),
            Manifest::Index(_)
        ));
    }

    #[test]
    fn image_manifests() {
        let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
        let docker = json!({
            "schemaVersion": 2,
            "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
            "config": {"mediaType": "application/vnd.docker.container.image.v1+json", "digest": d('1'), "size": 10},
            "layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "digest": d('2'), "size": 100}]
        });
        let Manifest::Image { config, layers } =
            parse_manifest("", docker.to_string().as_bytes()).unwrap()
        else {
            panic!()
        };
        assert_eq!(config.digest, d('1'));
        assert_eq!(layers[0].digest, d('2'));
        let oci = json!({
            "schemaVersion": 2,
            "config": {"digest": d('3')},
            "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": d('4')}]
        });
        assert!(matches!(
            parse_manifest(
                "application/vnd.oci.image.manifest.v1+json",
                oci.to_string().as_bytes()
            )
            .unwrap(),
            Manifest::Image { .. }
        ));
        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')}]});
        assert!(parse_manifest("", zstd.to_string().as_bytes()).is_err());
        let evil = json!({"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": "sha256:../../x"}, "layers": [{"digest": d('4')}]});
        assert!(parse_manifest("", evil.to_string().as_bytes()).is_err());
        assert!(parse_manifest("", br#"{"schemaVersion": 1}"#).is_err());
    }

    #[test]
    fn challenges_and_urls() {
        let (realm, service, scope) = parse_challenge(
            r#"Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/nginx:pull""#,
        )
        .unwrap();
        assert_eq!(realm, "https://auth.docker.io/token");
        assert_eq!(service.as_deref(), Some("registry.docker.io"));
        assert_eq!(scope.as_deref(), Some("repository:library/nginx:pull"));
        let (realm, service, _) =
            parse_challenge(r#"Bearer realm="https://ghcr.io/token",service="ghcr.io""#).unwrap();
        assert_eq!(
            (realm.as_str(), service.as_deref()),
            ("https://ghcr.io/token", Some("ghcr.io"))
        );
        assert!(parse_challenge("Basic realm=x").is_none());
        let u = parse_url("https://r.io:5000/v2/x?y=1").unwrap();
        assert_eq!(
            (u.host.as_str(), u.port, u.path.as_str()),
            ("r.io", 5000, "/v2/x?y=1")
        );
        assert!(parse_url("http://r.io/").is_err());
        assert!(parse_url("https://user@r.io/").is_err());
        assert!(digest_hex("sha256:ABC").is_err());
    }

    #[test]
    fn image_config_parse() {
        let c = image_config(br#"{"os":"linux","config":{"Cmd":["sh"],"Env":["A=1"],"User":"1"}}"#)
            .unwrap();
        assert_eq!(c.cmd, Some(vec!["sh".to_string()]));
        assert!(image_config(br#"{"os":"windows","config":{}}"#).is_err());
    }
}