oci-zero 0.3.0

A no-std, allocation-free streaming core for OCI registries
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
//! Callback-driven, allocation-free OCI graph traversal.

use crate::{
    digest::Digest,
    metadata::{Descriptor, Document, DocumentKind, ImageConfig, ImageIndex, ImageManifest},
    reference::{Reference, Selector},
};

pub const OCI_IMAGE_CONFIG: &str = "application/vnd.oci.image.config.v1+json";
pub const DOCKER_IMAGE_CONFIG: &str = "application/vnd.docker.container.image.v1+json";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ManifestReference<'a> {
    Tag(&'a str),
    Digest(Digest),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Selection {
    Skip,
    Pull,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlobAction {
    Skip,
    Fetch,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlobKind {
    Config,
    Layer { diff_id: Option<Digest> },
}

/// Receives streamed blob bytes from a [`Fetcher`].
pub trait BlobSink {
    fn chunk(&mut self, bytes: &[u8]);

    fn cancelled(&self) -> bool {
        false
    }
}

/// Supplies verified registry objects to the transport-independent pull walk.
///
/// Implementations must verify manifest digest references and each blob
/// descriptor's size and digest before returning success.
pub trait Fetcher {
    type Error;

    async fn manifest(
        &mut self,
        reference: ManifestReference<'_>,
        destination: &mut [u8],
    ) -> Result<usize, Self::Error>;

    async fn blob<S: BlobSink>(
        &mut self,
        descriptor: Descriptor<'_>,
        sink: &mut S,
    ) -> Result<(), Self::Error>;
}

/// Selects manifests and consumes pull events without retaining graph lists.
pub trait PullVisitor {
    type Error;

    fn index(&mut self, _index: ImageIndex<'_>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn select_manifest(&mut self, _descriptor: Descriptor<'_>) -> Result<Selection, Self::Error> {
        Ok(Selection::Pull)
    }

    fn manifest(&mut self, _manifest: ImageManifest<'_>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn subject(&mut self, _descriptor: Descriptor<'_>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn begin_blob(
        &mut self,
        _kind: BlobKind,
        _descriptor: Descriptor<'_>,
    ) -> Result<BlobAction, Self::Error> {
        Ok(BlobAction::Fetch)
    }

    fn blob_data(&mut self, _kind: BlobKind, _bytes: &[u8]) -> Result<(), Self::Error> {
        Ok(())
    }

    fn end_blob(&mut self, _kind: BlobKind) -> Result<(), Self::Error> {
        Ok(())
    }
}

pub struct PullBuffers<'a> {
    pub root_manifest: &'a mut [u8],
    pub child_manifest: &'a mut [u8],
    pub config: &'a mut [u8],
}

/// Pulls a root manifest, selects index children, fetches configs, and streams
/// selected layers in manifest order.
pub async fn pull<F, V>(
    fetcher: &mut F,
    reference: Reference<'_>,
    buffers: PullBuffers<'_>,
    visitor: &mut V,
) -> Result<(), PullError<F::Error, V::Error>>
where
    F: Fetcher,
    V: PullVisitor,
{
    let root_reference = match reference.selector() {
        Selector::Tag(tag) => ManifestReference::Tag(tag),
        Selector::Digest(digest) => ManifestReference::Digest(digest),
    };
    let root_length = fetcher
        .manifest(root_reference, buffers.root_manifest)
        .await
        .map_err(PullError::Fetch)?;
    if root_length > buffers.root_manifest.len() {
        return Err(PullError::BufferContract);
    }
    let root =
        Document::parse(&buffers.root_manifest[..root_length]).map_err(PullError::Metadata)?;
    match root.kind() {
        DocumentKind::Manifest => {
            pull_manifest(
                fetcher,
                root.manifest().map_err(PullError::Metadata)?,
                buffers.config,
                visitor,
            )
            .await
        }
        DocumentKind::Index => {
            let index = root.index().map_err(PullError::Metadata)?;
            visitor.index(index).map_err(PullError::Visitor)?;
            for descriptor in index.manifests().map_err(PullError::Metadata)? {
                let descriptor = descriptor.map_err(PullError::Metadata)?;
                if visitor
                    .select_manifest(descriptor)
                    .map_err(PullError::Visitor)?
                    == Selection::Skip
                {
                    continue;
                }
                let length = fetcher
                    .manifest(
                        ManifestReference::Digest(descriptor.digest()),
                        buffers.child_manifest,
                    )
                    .await
                    .map_err(PullError::Fetch)?;
                if length > buffers.child_manifest.len() {
                    return Err(PullError::BufferContract);
                }
                let child = Document::parse(&buffers.child_manifest[..length])
                    .map_err(PullError::Metadata)?;
                if child.kind() != DocumentKind::Manifest {
                    return Err(PullError::NestedIndex);
                }
                pull_manifest(
                    fetcher,
                    child.manifest().map_err(PullError::Metadata)?,
                    buffers.config,
                    visitor,
                )
                .await?;
            }
            Ok(())
        }
    }
}

async fn pull_manifest<F, V>(
    fetcher: &mut F,
    manifest: ImageManifest<'_>,
    config_buffer: &mut [u8],
    visitor: &mut V,
) -> Result<(), PullError<F::Error, V::Error>>
where
    F: Fetcher,
    V: PullVisitor,
{
    visitor.manifest(manifest).map_err(PullError::Visitor)?;
    if let Some(subject) = manifest.subject().map_err(PullError::Metadata)? {
        visitor.subject(subject).map_err(PullError::Visitor)?;
    }

    let config = manifest.config().map_err(PullError::Metadata)?;
    let mut config_sink = BufferSink::new(config_buffer);
    fetcher
        .blob(config, &mut config_sink)
        .await
        .map_err(PullError::Fetch)?;
    let config_length = config_sink
        .finish()
        .map_err(|_| PullError::ConfigTooLarge)?;
    let action = visitor
        .begin_blob(BlobKind::Config, config)
        .map_err(PullError::Visitor)?;
    if action == BlobAction::Fetch {
        visitor
            .blob_data(BlobKind::Config, &config_buffer[..config_length])
            .map_err(PullError::Visitor)?;
        visitor
            .end_blob(BlobKind::Config)
            .map_err(PullError::Visitor)?;
    }

    let config_media_type = config.media_type();
    let image_config = config_media_type.decoded_eq_ascii(OCI_IMAGE_CONFIG)
        || config_media_type.decoded_eq_ascii(DOCKER_IMAGE_CONFIG);
    let mut diff_ids = if image_config {
        let config_document =
            ImageConfig::parse(&config_buffer[..config_length]).map_err(PullError::Metadata)?;
        let diff_ids = config_document.diff_ids().map_err(PullError::Metadata)?;
        if diff_ids.is_none() {
            return Err(PullError::MissingDiffIds);
        }
        diff_ids
    } else {
        // Artifact configs are media-type-defined blobs and need not be JSON.
        None
    };

    for descriptor in manifest.layers().map_err(PullError::Metadata)? {
        let descriptor = descriptor.map_err(PullError::Metadata)?;
        let diff_id = match diff_ids.as_mut() {
            Some(ids) => Some(
                ids.next()
                    .ok_or(PullError::DiffIdCount)?
                    .map_err(PullError::Metadata)?,
            ),
            None => None,
        };
        let kind = BlobKind::Layer { diff_id };
        let action = visitor
            .begin_blob(kind, descriptor)
            .map_err(PullError::Visitor)?;
        if action == BlobAction::Skip {
            continue;
        }
        let mut sink = VisitorSink {
            visitor,
            kind,
            error: None,
        };
        fetcher
            .blob(descriptor, &mut sink)
            .await
            .map_err(PullError::Fetch)?;
        if let Some(error) = sink.error {
            return Err(PullError::Visitor(error));
        }
        visitor.end_blob(kind).map_err(PullError::Visitor)?;
    }
    if diff_ids.as_mut().and_then(Iterator::next).is_some() {
        return Err(PullError::DiffIdCount);
    }
    Ok(())
}

struct BufferSink<'a> {
    buffer: &'a mut [u8],
    length: usize,
    overflow: bool,
}

impl<'a> BufferSink<'a> {
    fn new(buffer: &'a mut [u8]) -> Self {
        Self {
            buffer,
            length: 0,
            overflow: false,
        }
    }

    fn finish(&self) -> Result<usize, ()> {
        (!self.overflow).then_some(self.length).ok_or(())
    }
}

impl BlobSink for BufferSink<'_> {
    fn chunk(&mut self, bytes: &[u8]) {
        self.overflow |= crate::buffer::append(self.buffer, &mut self.length, bytes).is_err();
    }

    fn cancelled(&self) -> bool {
        self.overflow
    }
}

struct VisitorSink<'a, V: PullVisitor> {
    visitor: &'a mut V,
    kind: BlobKind,
    error: Option<V::Error>,
}

impl<V: PullVisitor> BlobSink for VisitorSink<'_, V> {
    fn chunk(&mut self, bytes: &[u8]) {
        if self.error.is_none() {
            self.error = self.visitor.blob_data(self.kind, bytes).err();
        }
    }

    fn cancelled(&self) -> bool {
        self.error.is_some()
    }
}

#[derive(Debug, derive_more::Display)]
pub enum PullError<F, V> {
    #[display("registry fetch failed: {_0}")]
    Fetch(F),
    #[display("pull visitor failed: {_0}")]
    Visitor(V),
    #[display("OCI metadata failed: {_0}")]
    Metadata(crate::metadata::MetadataError),
    #[display("image config exceeds its caller buffer")]
    ConfigTooLarge,
    #[display("image config is missing rootfs.diff_ids")]
    MissingDiffIds,
    #[display("layer and diff_id counts differ")]
    DiffIdCount,
    #[display("nested OCI indexes exceed this pull frame")]
    NestedIndex,
    #[display("fetcher returned an out-of-range length")]
    BufferContract,
}

#[cfg(test)]
mod tests {
    use core::{future::Future, task::Poll};
    use std::{string::ToString, sync::Arc, task::Wake};

    use super::{
        pull, BlobAction, BlobKind, BlobSink, BufferSink, Fetcher, ManifestReference, PullBuffers,
        PullError, PullVisitor, Selection, VisitorSink,
    };
    use crate::{metadata::Descriptor, reference::Reference};

    const MANIFEST: &[u8] = br#"{
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "artifactType": "application/example",
        "config": {
            "mediaType": "application/vnd.example.config",
            "digest": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
            "size": 8
        },
        "layers": [{
            "mediaType": "application/vnd.example.payload",
            "digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
            "size": 5
        }]
    }"#;

    const ESCAPED_MEDIA_TYPE_MANIFEST: &[u8] = br#"{
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": {
            "mediaType": "application\/vnd.oci.image.config.v1+json",
            "digest": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
            "size": 115
        },
        "layers": [{
            "mediaType": "application/vnd.oci.image.layer.v1.tar",
            "digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
            "size": 5
        }]
    }"#;

    const IMAGE_CONFIG: &[u8] = br#"{"rootfs":{"type":"layers","diff_ids":["sha256:2222222222222222222222222222222222222222222222222222222222222222"]}}"#;

    const INDEX: &[u8] = br#"{
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.index.v1+json",
        "manifests": [{
            "mediaType": "application/vnd.oci.image.manifest.v1+json",
            "digest": "sha256:3333333333333333333333333333333333333333333333333333333333333333",
            "size": 0
        }]
    }"#;

    struct MockFetcher;

    impl Fetcher for MockFetcher {
        type Error = ();

        async fn manifest(
            &mut self,
            _reference: ManifestReference<'_>,
            destination: &mut [u8],
        ) -> Result<usize, Self::Error> {
            destination[..MANIFEST.len()].copy_from_slice(MANIFEST);
            Ok(MANIFEST.len())
        }

        async fn blob<S: BlobSink>(
            &mut self,
            descriptor: Descriptor<'_>,
            sink: &mut S,
        ) -> Result<(), Self::Error> {
            if descriptor.media_type().as_str() == Some("application/vnd.example.config") {
                sink.chunk(b"not json");
            } else {
                sink.chunk(b"layer");
            }
            Ok(())
        }
    }

    struct EscapedMediaTypeFetcher;

    impl Fetcher for EscapedMediaTypeFetcher {
        type Error = ();

        async fn manifest(
            &mut self,
            _reference: ManifestReference<'_>,
            destination: &mut [u8],
        ) -> Result<usize, Self::Error> {
            destination[..ESCAPED_MEDIA_TYPE_MANIFEST.len()]
                .copy_from_slice(ESCAPED_MEDIA_TYPE_MANIFEST);
            Ok(ESCAPED_MEDIA_TYPE_MANIFEST.len())
        }

        async fn blob<S: BlobSink>(
            &mut self,
            descriptor: Descriptor<'_>,
            sink: &mut S,
        ) -> Result<(), Self::Error> {
            if descriptor.media_type().encoded().contains("\\/") {
                sink.chunk(IMAGE_CONFIG);
            } else {
                sink.chunk(b"layer");
            }
            Ok(())
        }
    }

    #[derive(Default)]
    struct IndexFetcher {
        manifest_calls: usize,
    }

    impl Fetcher for IndexFetcher {
        type Error = ();

        async fn manifest(
            &mut self,
            _reference: ManifestReference<'_>,
            destination: &mut [u8],
        ) -> Result<usize, Self::Error> {
            let document = if self.manifest_calls == 0 {
                INDEX
            } else {
                MANIFEST
            };
            self.manifest_calls += 1;
            destination[..document.len()].copy_from_slice(document);
            Ok(document.len())
        }

        async fn blob<S: BlobSink>(
            &mut self,
            descriptor: Descriptor<'_>,
            sink: &mut S,
        ) -> Result<(), Self::Error> {
            if descriptor.media_type().as_str() == Some("application/vnd.example.config") {
                sink.chunk(b"not json");
            } else {
                sink.chunk(b"layer");
            }
            Ok(())
        }
    }

    #[derive(Default)]
    struct Visitor {
        config_bytes: usize,
        layer_bytes: usize,
        layer_diff_id_was_none: bool,
        layer_diff_id_was_some: bool,
    }

    impl PullVisitor for Visitor {
        type Error = ();

        fn begin_blob(
            &mut self,
            kind: BlobKind,
            _descriptor: Descriptor<'_>,
        ) -> Result<BlobAction, Self::Error> {
            if let BlobKind::Layer { diff_id } = kind {
                self.layer_diff_id_was_none = diff_id.is_none();
                self.layer_diff_id_was_some = diff_id.is_some();
            }
            Ok(BlobAction::Fetch)
        }

        fn blob_data(&mut self, kind: BlobKind, bytes: &[u8]) -> Result<(), Self::Error> {
            match kind {
                BlobKind::Config => self.config_bytes += bytes.len(),
                BlobKind::Layer { .. } => self.layer_bytes += bytes.len(),
            }
            Ok(())
        }
    }

    struct SkipVisitor;

    impl PullVisitor for SkipVisitor {
        type Error = ();

        fn select_manifest(
            &mut self,
            _descriptor: Descriptor<'_>,
        ) -> Result<Selection, Self::Error> {
            Ok(Selection::Skip)
        }
    }

    #[test]
    fn pulls_non_json_artifact_configs() {
        let mut fetcher = MockFetcher;
        let mut visitor = Visitor::default();
        let mut root = [0; 1024];
        let mut child = [0; 1024];
        let mut config = [0; 64];
        let future = pull(
            &mut fetcher,
            Reference::parse("oci://example.com/artifact:latest").unwrap(),
            PullBuffers {
                root_manifest: &mut root,
                child_manifest: &mut child,
                config: &mut config,
            },
            &mut visitor,
        );
        assert!(block_on_ready(future).is_ok());
        assert_eq!(visitor.config_bytes, 8);
        assert_eq!(visitor.layer_bytes, 5);
        assert!(visitor.layer_diff_id_was_none);
    }

    #[test]
    fn recognizes_escaped_image_config_media_types() {
        let mut fetcher = EscapedMediaTypeFetcher;
        let mut visitor = Visitor::default();
        let mut root = [0; 1024];
        let mut child = [0; 1024];
        let mut config = [0; 256];
        let future = pull(
            &mut fetcher,
            Reference::parse("oci://example.com/image:latest").unwrap(),
            PullBuffers {
                root_manifest: &mut root,
                child_manifest: &mut child,
                config: &mut config,
            },
            &mut visitor,
        );
        assert!(block_on_ready(future).is_ok());
        assert!(visitor.layer_diff_id_was_some);
    }

    #[test]
    fn accepts_manifest_buffers_at_their_exact_contract_size() {
        let mut fetcher = MockFetcher;
        let mut visitor = Visitor::default();
        let mut root = [0; MANIFEST.len()];
        let mut child = [0; 1];
        let mut config = [0; 8];
        let result = block_on_ready(pull(
            &mut fetcher,
            Reference::parse("oci://example.com/artifact:latest").unwrap(),
            PullBuffers {
                root_manifest: &mut root,
                child_manifest: &mut child,
                config: &mut config,
            },
            &mut visitor,
        ));
        assert!(result.is_ok());
    }

    #[test]
    fn pulls_index_children_with_exact_and_roomy_buffers() {
        for exact in [true, false] {
            let mut fetcher = IndexFetcher::default();
            let mut visitor = Visitor::default();
            let mut root = [0; INDEX.len()];
            let mut child = [0; 1024];
            let child = if exact {
                &mut child[..MANIFEST.len()]
            } else {
                &mut child[..]
            };
            let mut config = [0; 8];
            let result = block_on_ready(pull(
                &mut fetcher,
                Reference::parse("oci://example.com/artifact:latest").unwrap(),
                PullBuffers {
                    root_manifest: &mut root,
                    child_manifest: child,
                    config: &mut config,
                },
                &mut visitor,
            ));
            assert!(result.is_ok());
            assert_eq!(fetcher.manifest_calls, 2);
        }
    }

    #[test]
    fn skips_unselected_index_children() {
        let mut fetcher = IndexFetcher::default();
        let mut visitor = SkipVisitor;
        let mut root = [0; INDEX.len()];
        let mut child = [0; MANIFEST.len()];
        let mut config = [0; 8];
        let result = block_on_ready(pull(
            &mut fetcher,
            Reference::parse("oci://example.com/artifact:latest").unwrap(),
            PullBuffers {
                root_manifest: &mut root,
                child_manifest: &mut child,
                config: &mut config,
            },
            &mut visitor,
        ));
        assert!(result.is_ok());
        assert_eq!(fetcher.manifest_calls, 1);
    }

    #[test]
    fn reports_sink_cancellation_state() {
        struct DefaultSink;
        impl BlobSink for DefaultSink {
            fn chunk(&mut self, _bytes: &[u8]) {}
        }
        assert!(!DefaultSink.cancelled());

        let mut buffer = [0; 1];
        let mut sink = BufferSink::new(&mut buffer);
        assert!(!sink.cancelled());
        sink.chunk(b"ab");
        assert!(sink.cancelled());

        struct FailingVisitor;
        impl PullVisitor for FailingVisitor {
            type Error = &'static str;

            fn blob_data(&mut self, _kind: BlobKind, _bytes: &[u8]) -> Result<(), Self::Error> {
                Err("stop")
            }
        }
        let mut visitor = FailingVisitor;
        let mut sink = VisitorSink {
            visitor: &mut visitor,
            kind: BlobKind::Config,
            error: None,
        };
        assert!(!sink.cancelled());
        sink.chunk(b"data");
        assert!(sink.cancelled());
    }

    #[test]
    fn formats_pull_errors() {
        let error = PullError::<&str, &str>::BufferContract;
        assert_eq!(error.to_string(), "fetcher returned an out-of-range length");
    }

    fn block_on_ready<F: Future>(future: F) -> F::Output {
        struct NoopWake;
        impl Wake for NoopWake {
            fn wake(self: Arc<Self>) {}
        }

        let waker = std::task::Waker::from(Arc::new(NoopWake));
        let mut context = core::task::Context::from_waker(&waker);
        let mut future = core::pin::pin!(future);
        match future.as_mut().poll(&mut context) {
            Poll::Ready(output) => output,
            Poll::Pending => panic!("in-memory pull unexpectedly yielded"),
        }
    }
}