Skip to main content

oci_zero/
layer.rs

1//! Verified, allocation-free OCI layer decoding.
2
3use core::fmt;
4
5use crate::{
6    digest::{Digest, Verifier, VerifyError},
7    tar::{
8        Archive, ArchiveError, ArchiveFinishError, EntryExtractor, ExtractError, FinishError,
9        TransactionalLayerSink,
10    },
11};
12
13pub const OCI_LAYER_TAR: &str = "application/vnd.oci.image.layer.v1.tar";
14pub const OCI_LAYER_GZIP: &str = "application/vnd.oci.image.layer.v1.tar+gzip";
15pub const OCI_LAYER_ZSTD: &str = "application/vnd.oci.image.layer.v1.tar+zstd";
16pub const OCI_NONDISTRIBUTABLE_TAR: &str =
17    "application/vnd.oci.image.layer.nondistributable.v1.tar";
18pub const OCI_NONDISTRIBUTABLE_GZIP: &str =
19    "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip";
20pub const OCI_NONDISTRIBUTABLE_ZSTD: &str =
21    "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd";
22pub const DOCKER_LAYER_GZIP: &str = "application/vnd.docker.image.rootfs.diff.tar.gzip";
23pub const DOCKER_FOREIGN_LAYER_GZIP: &str =
24    "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip";
25pub const DOCKER_LAYER_TAR: &str = "application/vnd.docker.image.rootfs.diff.tar";
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum Encoding {
29    Tar,
30    Gzip,
31    Zstd,
32}
33
34pub fn encoding(media_type: &str) -> Result<Encoding, LayerFormatError> {
35    match media_type {
36        OCI_LAYER_TAR | OCI_NONDISTRIBUTABLE_TAR | DOCKER_LAYER_TAR => Ok(Encoding::Tar),
37        OCI_LAYER_GZIP
38        | OCI_NONDISTRIBUTABLE_GZIP
39        | DOCKER_LAYER_GZIP
40        | DOCKER_FOREIGN_LAYER_GZIP => Ok(Encoding::Gzip),
41        OCI_LAYER_ZSTD | OCI_NONDISTRIBUTABLE_ZSTD => Ok(Encoding::Zstd),
42        _ => Err(LayerFormatError::UnsupportedMediaType),
43    }
44}
45
46// Keeping codec state inline is intentional: indirection would require an
47// allocator or a second caller-owned object with a more fragile lifetime API.
48#[allow(clippy::large_enum_variant)]
49pub enum Decoder<'a> {
50    Tar,
51    #[cfg(feature = "gzip")]
52    Gzip(gzip_zero::Decoder<'a>),
53    #[cfg(feature = "zstd")]
54    Zstd(zstd_zero::Decoder<'a>),
55    #[doc(hidden)]
56    _Lifetime(core::marker::PhantomData<&'a mut [u8]>),
57}
58
59impl<'a> Decoder<'a> {
60    pub const fn tar() -> Self {
61        Self::Tar
62    }
63
64    #[cfg(feature = "gzip")]
65    pub fn gzip(buffers: gzip_zero::DecoderBuffers<'a>) -> Result<Self, LayerFormatError> {
66        Ok(Self::Gzip(
67            gzip_zero::Decoder::new(buffers).map_err(LayerFormatError::Gzip)?,
68        ))
69    }
70
71    #[cfg(feature = "zstd")]
72    pub fn zstd(buffers: zstd_zero::DecoderBuffers<'a>) -> Result<Self, LayerFormatError> {
73        Ok(Self::Zstd(
74            zstd_zero::Decoder::new(buffers).map_err(LayerFormatError::Zstd)?,
75        ))
76    }
77
78    pub fn decode<'decoder>(
79        &'decoder mut self,
80        input: &'decoder [u8],
81    ) -> Result<DecodeStep<'decoder>, LayerFormatError> {
82        match self {
83            Self::Tar => Ok(if input.is_empty() {
84                DecodeStep::NeedInput { consumed: 0 }
85            } else {
86                DecodeStep::Output {
87                    consumed: input.len(),
88                    bytes: input,
89                }
90            }),
91            #[cfg(feature = "gzip")]
92            Self::Gzip(decoder) => Ok(
93                match decoder.decode(input).map_err(LayerFormatError::Gzip)? {
94                    gzip_zero::DecodeStep::NeedInput { consumed } => {
95                        DecodeStep::NeedInput { consumed }
96                    }
97                    gzip_zero::DecodeStep::MemberStarted { consumed, .. }
98                    | gzip_zero::DecodeStep::MemberFinished { consumed } => {
99                        DecodeStep::Progress { consumed }
100                    }
101                    gzip_zero::DecodeStep::Output { consumed, bytes } => {
102                        DecodeStep::Output { consumed, bytes }
103                    }
104                },
105            ),
106            #[cfg(feature = "zstd")]
107            Self::Zstd(decoder) => Ok(
108                match decoder.decode(input).map_err(LayerFormatError::Zstd)? {
109                    zstd_zero::DecodeStep::NeedInput { consumed } => {
110                        DecodeStep::NeedInput { consumed }
111                    }
112                    zstd_zero::DecodeStep::FrameStarted { consumed, .. }
113                    | zstd_zero::DecodeStep::FrameFinished { consumed, .. } => {
114                        DecodeStep::Progress { consumed }
115                    }
116                    zstd_zero::DecodeStep::Output { consumed, bytes } => {
117                        DecodeStep::Output { consumed, bytes }
118                    }
119                },
120            ),
121            Self::_Lifetime(_) => unreachable!(),
122        }
123    }
124
125    pub fn finish(&self) -> Result<(), LayerFormatError> {
126        match self {
127            Self::Tar => Ok(()),
128            #[cfg(feature = "gzip")]
129            Self::Gzip(decoder) => decoder.finish().map_err(LayerFormatError::Gzip),
130            #[cfg(feature = "zstd")]
131            Self::Zstd(decoder) => decoder.finish().map_err(LayerFormatError::Zstd),
132            Self::_Lifetime(_) => unreachable!(),
133        }
134    }
135}
136
137#[derive(Debug, Eq, PartialEq)]
138pub enum DecodeStep<'a> {
139    NeedInput { consumed: usize },
140    Progress { consumed: usize },
141    Output { consumed: usize, bytes: &'a [u8] },
142}
143
144impl DecodeStep<'_> {
145    pub const fn consumed(&self) -> usize {
146        match self {
147            Self::NeedInput { consumed }
148            | Self::Progress { consumed }
149            | Self::Output { consumed, .. } => *consumed,
150        }
151    }
152}
153
154pub struct VerifiedDecoder<'a> {
155    decoder: Decoder<'a>,
156    compressed: Verifier,
157    uncompressed: Option<Verifier>,
158    decompressed_size: u64,
159}
160
161/// Verifies and decodes a layer while extracting one regular tar entry.
162pub struct VerifiedEntryExtractor<'decoder, 'target> {
163    decoder: VerifiedDecoder<'decoder>,
164    extractor: EntryExtractor<'target>,
165    extracted_size: u64,
166}
167
168impl<'decoder, 'target> VerifiedEntryExtractor<'decoder, 'target> {
169    pub const fn new(decoder: VerifiedDecoder<'decoder>, target: &'target [u8]) -> Self {
170        Self {
171            decoder,
172            extractor: EntryExtractor::new(target),
173            extracted_size: 0,
174        }
175    }
176
177    pub fn push<E>(
178        &mut self,
179        input: &[u8],
180        mut output: impl FnMut(&[u8]) -> Result<(), E>,
181    ) -> Result<(), EntryLayerError<E>> {
182        let extractor = &mut self.extractor;
183        let extracted_size = &mut self.extracted_size;
184        self.decoder
185            .push(input, |decoded| {
186                extract_output(extractor, extracted_size, decoded, &mut output)
187            })
188            .map_err(EntryLayerError::Layer)
189    }
190
191    pub fn finish<E>(
192        &mut self,
193        mut output: impl FnMut(&[u8]) -> Result<(), E>,
194    ) -> Result<(), EntryLayerError<E>> {
195        let extractor = &mut self.extractor;
196        let extracted_size = &mut self.extracted_size;
197        self.decoder
198            .finish(|decoded| extract_output(extractor, extracted_size, decoded, &mut output))
199            .map_err(EntryLayerError::Layer)?;
200        self.extractor.finish().map_err(EntryLayerError::Finish)
201    }
202
203    pub const fn compressed_size(&self) -> u64 {
204        self.decoder.compressed_size()
205    }
206
207    pub const fn decompressed_size(&self) -> u64 {
208        self.decoder.decompressed_size()
209    }
210
211    pub const fn extracted_size(&self) -> u64 {
212        self.extracted_size
213    }
214
215    pub const fn found(&self) -> bool {
216        self.extractor.found()
217    }
218}
219
220fn extract_output<E>(
221    extractor: &mut EntryExtractor<'_>,
222    extracted_size: &mut u64,
223    decoded: &[u8],
224    output: &mut impl FnMut(&[u8]) -> Result<(), E>,
225) -> Result<(), ExtractError<E>> {
226    extractor.push(decoded, |contents| {
227        output(contents)?;
228        *extracted_size += contents.len() as u64;
229        Ok(())
230    })
231}
232
233#[derive(Debug)]
234pub enum EntryLayerError<E> {
235    Layer(LayerError<ExtractError<E>>),
236    Finish(FinishError),
237}
238
239impl<E: fmt::Display> fmt::Display for EntryLayerError<E> {
240    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
241        match self {
242            Self::Layer(error) => write!(formatter, "entry layer failed: {error}"),
243            Self::Finish(error) => write!(formatter, "entry extraction failed: {error}"),
244        }
245    }
246}
247
248/// Transactionally decodes, verifies, parses, and applies one OCI layer.
249pub struct LayerApplier<'decoder, 'archive> {
250    decoder: VerifiedDecoder<'decoder>,
251    archive: Archive<'archive>,
252    state: ApplyState,
253}
254
255#[derive(Clone, Copy, Debug, Eq, PartialEq)]
256enum ApplyState {
257    Ready,
258    Applying,
259    Failed,
260    Finished,
261}
262
263impl<'decoder, 'archive> LayerApplier<'decoder, 'archive> {
264    pub fn new(decoder: VerifiedDecoder<'decoder>, archive: Archive<'archive>) -> Self {
265        Self {
266            decoder,
267            archive,
268            state: ApplyState::Ready,
269        }
270    }
271
272    pub fn push<S: TransactionalLayerSink>(
273        &mut self,
274        input: &[u8],
275        sink: &mut S,
276    ) -> Result<(), ApplyError<S::Error>> {
277        match self.state {
278            ApplyState::Ready => {
279                sink.begin_layer().map_err(ApplyError::Sink)?;
280                self.state = ApplyState::Applying;
281            }
282            ApplyState::Applying => {}
283            ApplyState::Failed | ApplyState::Finished => return Err(ApplyError::InvalidState),
284        }
285        let (decoder, archive) = (&mut self.decoder, &mut self.archive);
286        let result = decoder.push(input, |bytes| archive.push(bytes, sink));
287        if let Err(error) = result {
288            sink.abort_layer();
289            self.state = ApplyState::Failed;
290            return Err(map_apply_error(error));
291        }
292        Ok(())
293    }
294
295    pub fn finish<S: TransactionalLayerSink>(
296        &mut self,
297        sink: &mut S,
298    ) -> Result<(), ApplyError<S::Error>> {
299        if self.state == ApplyState::Ready {
300            sink.begin_layer().map_err(ApplyError::Sink)?;
301            self.state = ApplyState::Applying;
302        }
303        if self.state != ApplyState::Applying {
304            return Err(ApplyError::InvalidState);
305        }
306        let (decoder, archive) = (&mut self.decoder, &mut self.archive);
307        if let Err(error) = decoder.finish(|bytes| archive.push(bytes, sink)) {
308            sink.abort_layer();
309            self.state = ApplyState::Failed;
310            return Err(map_apply_error(error));
311        }
312        if let Err(error) = archive.finish() {
313            sink.abort_layer();
314            self.state = ApplyState::Failed;
315            return Err(ApplyError::ArchiveFinish(error));
316        }
317        if let Err(error) = sink.commit_layer() {
318            sink.abort_layer();
319            self.state = ApplyState::Failed;
320            return Err(ApplyError::Sink(error));
321        }
322        self.state = ApplyState::Finished;
323        Ok(())
324    }
325}
326
327#[derive(Debug)]
328pub enum ApplyError<E> {
329    Format(LayerFormatError),
330    Integrity(VerifyError),
331    Archive(ArchiveError<E>),
332    ArchiveFinish(ArchiveFinishError),
333    Sink(E),
334    InvalidState,
335}
336
337impl<E: fmt::Display> fmt::Display for ApplyError<E> {
338    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
339        match self {
340            Self::Format(error) => write!(formatter, "layer format error: {error}"),
341            Self::Integrity(error) => write!(formatter, "layer integrity error: {error}"),
342            Self::Archive(error) => write!(formatter, "layer archive error: {error}"),
343            Self::ArchiveFinish(error) => write!(formatter, "layer archive error: {error}"),
344            Self::Sink(error) => write!(formatter, "layer sink failed: {error}"),
345            Self::InvalidState => formatter.write_str("invalid layer application state"),
346        }
347    }
348}
349
350fn map_apply_error<E>(error: LayerError<ArchiveError<E>>) -> ApplyError<E> {
351    match error {
352        LayerError::Format(error) => ApplyError::Format(error),
353        LayerError::Integrity(error) => ApplyError::Integrity(error),
354        LayerError::Output(error) => ApplyError::Archive(error),
355    }
356}
357
358impl<'a> VerifiedDecoder<'a> {
359    pub fn new(
360        decoder: Decoder<'a>,
361        compressed_digest: Digest,
362        compressed_size: u64,
363        diff_id: Digest,
364    ) -> Self {
365        Self {
366            decoder,
367            compressed: Verifier::new(compressed_digest, compressed_size),
368            uncompressed: Some(Verifier::digest_only(diff_id)),
369            decompressed_size: 0,
370        }
371    }
372
373    /// Creates a decoder that verifies the compressed descriptor only.
374    ///
375    /// OCI artifacts commonly use layer archives without an image config's
376    /// `rootfs.diff_ids`. Decoded byte accounting remains available, but no
377    /// uncompressed digest is expected or checked.
378    pub fn compressed_only(
379        decoder: Decoder<'a>,
380        compressed_digest: Digest,
381        compressed_size: u64,
382    ) -> Self {
383        Self {
384            decoder,
385            compressed: Verifier::new(compressed_digest, compressed_size),
386            uncompressed: None,
387            decompressed_size: 0,
388        }
389    }
390
391    pub fn push<E>(
392        &mut self,
393        input: &[u8],
394        mut output: impl FnMut(&[u8]) -> Result<(), E>,
395    ) -> Result<(), LayerError<E>> {
396        self.compressed
397            .update(input)
398            .map_err(LayerError::Integrity)?;
399        let mut remaining = input;
400        let mut turns_without_bytes = 0usize;
401        while !remaining.is_empty() {
402            let step = self.decoder.decode(remaining).map_err(LayerError::Format)?;
403            let consumed = step.consumed();
404            if let DecodeStep::Output { bytes, .. } = step {
405                self.decompressed_size += bytes.len() as u64;
406                if let Some(uncompressed) = &mut self.uncompressed {
407                    uncompressed.update(bytes).map_err(LayerError::Integrity)?;
408                }
409                output(bytes).map_err(LayerError::Output)?;
410            }
411            if consumed == 0 {
412                turns_without_bytes += 1;
413                if turns_without_bytes > 16 {
414                    return Err(LayerError::Format(LayerFormatError::DecoderStalled));
415                }
416            } else {
417                turns_without_bytes = 0;
418                remaining = &remaining[consumed..];
419            }
420        }
421        Ok(())
422    }
423
424    pub const fn compressed_size(&self) -> u64 {
425        self.compressed.actual_size()
426    }
427
428    pub const fn decompressed_size(&self) -> u64 {
429        self.decompressed_size
430    }
431
432    pub fn finish<E>(
433        &mut self,
434        mut output: impl FnMut(&[u8]) -> Result<(), E>,
435    ) -> Result<(), LayerError<E>> {
436        loop {
437            match self.decoder.decode(&[]).map_err(LayerError::Format)? {
438                DecodeStep::Output { bytes, .. } => {
439                    self.decompressed_size += bytes.len() as u64;
440                    if let Some(uncompressed) = &mut self.uncompressed {
441                        uncompressed.update(bytes).map_err(LayerError::Integrity)?;
442                    }
443                    output(bytes).map_err(LayerError::Output)?;
444                }
445                DecodeStep::Progress { .. } => {}
446                DecodeStep::NeedInput { .. } => break,
447            }
448        }
449        self.decoder.finish().map_err(LayerError::Format)?;
450        self.compressed.finish().map_err(LayerError::Integrity)?;
451        if let Some(uncompressed) = &self.uncompressed {
452            uncompressed.finish().map_err(LayerError::Integrity)?;
453        }
454        Ok(())
455    }
456}
457
458#[derive(Debug)]
459pub enum LayerError<E> {
460    Format(LayerFormatError),
461    Integrity(VerifyError),
462    Output(E),
463}
464
465impl<E: fmt::Display> fmt::Display for LayerError<E> {
466    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
467        match self {
468            Self::Format(error) => write!(formatter, "layer format error: {error}"),
469            Self::Integrity(error) => write!(formatter, "layer integrity error: {error}"),
470            Self::Output(error) => write!(formatter, "layer output error: {error}"),
471        }
472    }
473}
474
475#[derive(Debug)]
476pub enum LayerFormatError {
477    UnsupportedMediaType,
478    EncodingDisabled(Encoding),
479    DecoderStalled,
480    #[cfg(feature = "gzip")]
481    Gzip(gzip_zero::DecodeError),
482    #[cfg(feature = "zstd")]
483    Zstd(zstd_zero::DecodeError),
484}
485
486impl fmt::Display for LayerFormatError {
487    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
488        match self {
489            Self::UnsupportedMediaType => formatter.write_str("unsupported OCI layer media type"),
490            Self::EncodingDisabled(encoding) => {
491                write!(formatter, "{encoding:?} layer support is disabled")
492            }
493            Self::DecoderStalled => formatter.write_str("layer decoder stopped making progress"),
494            #[cfg(feature = "gzip")]
495            Self::Gzip(error) => write!(formatter, "{error}"),
496            #[cfg(feature = "zstd")]
497            Self::Zstd(error) => write!(formatter, "{error}"),
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use sha2::{Digest as _, Sha256};
505
506    use super::{Decoder, LayerApplier, VerifiedDecoder, VerifiedEntryExtractor};
507    use crate::{
508        digest::Digest,
509        tar::{Archive, ArchiveBuffers, Entry, LayerEventSink, TransactionalLayerSink},
510    };
511
512    #[derive(Default)]
513    struct TransactionSink {
514        began: bool,
515        committed: bool,
516        aborted: bool,
517    }
518
519    impl LayerEventSink for TransactionSink {
520        type Error = ();
521
522        fn begin_entry(&mut self, _entry: Entry<'_>) -> Result<(), Self::Error> {
523            Ok(())
524        }
525
526        fn entry_data(&mut self, _bytes: &[u8]) -> Result<(), Self::Error> {
527            Ok(())
528        }
529
530        fn end_entry(&mut self) -> Result<(), Self::Error> {
531            Ok(())
532        }
533
534        fn whiteout(&mut self, _path: &[u8]) -> Result<(), Self::Error> {
535            Ok(())
536        }
537
538        fn opaque_directory(&mut self, _path: &[u8]) -> Result<(), Self::Error> {
539            Ok(())
540        }
541    }
542
543    impl TransactionalLayerSink for TransactionSink {
544        fn begin_layer(&mut self) -> Result<(), Self::Error> {
545            self.began = true;
546            Ok(())
547        }
548
549        fn commit_layer(&mut self) -> Result<(), Self::Error> {
550            self.committed = true;
551            Ok(())
552        }
553
554        fn abort_layer(&mut self) {
555            self.aborted = true;
556        }
557    }
558
559    #[test]
560    fn verifies_uncompressed_layers() {
561        let bytes = b"tar bytes";
562        let digest = Digest::from_bytes(Sha256::digest(bytes).into());
563        let mut decoder = VerifiedDecoder::new(Decoder::tar(), digest, bytes.len() as u64, digest);
564        let mut output = [0; 9];
565        let mut length = 0;
566        decoder
567            .push(bytes, |chunk| {
568                output[length..length + chunk.len()].copy_from_slice(chunk);
569                length += chunk.len();
570                Ok::<_, ()>(())
571            })
572            .unwrap();
573        decoder.finish(|_| Ok::<_, ()>(())).unwrap();
574        assert_eq!(&output, bytes);
575    }
576
577    #[test]
578    fn compressed_only_accepts_content_without_a_diff_id() {
579        let bytes = b"artifact contents";
580        let digest = Digest::from_bytes(Sha256::digest(bytes).into());
581        let mut decoder =
582            VerifiedDecoder::compressed_only(Decoder::tar(), digest, bytes.len() as u64);
583        decoder.push(bytes, |_| Ok::<_, ()>(())).unwrap();
584        decoder.finish(|_| Ok::<_, ()>(())).unwrap();
585        assert_eq!(decoder.decompressed_size(), bytes.len() as u64);
586    }
587
588    #[test]
589    fn compressed_only_still_verifies_descriptor_digest_and_size() {
590        let bytes = b"artifact contents";
591        let digest = Digest::from_bytes(Sha256::digest(bytes).into());
592        let mut wrong_digest = VerifiedDecoder::compressed_only(
593            Decoder::tar(),
594            Digest::from_bytes([9; 32]),
595            bytes.len() as u64,
596        );
597        wrong_digest.push(bytes, |_| Ok::<_, ()>(())).unwrap();
598        assert!(wrong_digest.finish(|_| Ok::<_, ()>(())).is_err());
599
600        let mut wrong_size = VerifiedDecoder::compressed_only(Decoder::tar(), digest, 1);
601        wrong_size.push(bytes, |_| Ok::<_, ()>(())).unwrap();
602        assert!(wrong_size.finish(|_| Ok::<_, ()>(())).is_err());
603    }
604
605    #[test]
606    fn verifies_and_extracts_one_entry() {
607        let mut tar = [0u8; 2048];
608        tar[..6].copy_from_slice(b"wanted");
609        write_octal(&mut tar[100..108], 0o644);
610        write_octal(&mut tar[124..136], 5);
611        tar[148..156].fill(b' ');
612        tar[156] = b'0';
613        let checksum = tar[..512].iter().map(|byte| u64::from(*byte)).sum();
614        write_octal(&mut tar[148..156], checksum);
615        tar[512..517].copy_from_slice(b"hello");
616
617        let digest = Digest::from_bytes(Sha256::digest(tar).into());
618        let decoder = VerifiedDecoder::new(Decoder::tar(), digest, tar.len() as u64, digest);
619        let mut extractor = VerifiedEntryExtractor::new(decoder, b"wanted");
620        let mut output = [0u8; 5];
621        let mut length = 0;
622        for fragment in tar.chunks(7) {
623            extractor
624                .push(fragment, |bytes| {
625                    output[length..length + bytes.len()].copy_from_slice(bytes);
626                    length += bytes.len();
627                    Ok::<_, ()>(())
628                })
629                .unwrap();
630        }
631        extractor.finish(|_| Ok::<_, ()>(())).unwrap();
632        assert_eq!(&output, b"hello");
633        assert_eq!(extractor.decompressed_size(), tar.len() as u64);
634        assert_eq!(extractor.extracted_size(), 5);
635    }
636
637    fn write_octal(field: &mut [u8], value: u64) {
638        field.fill(b'0');
639        let digits = field.len() - 1;
640        field[digits] = 0;
641        let mut value = value;
642        for byte in field[..digits].iter_mut().rev() {
643            *byte = b'0' + (value & 7) as u8;
644            value >>= 3;
645        }
646    }
647
648    #[test]
649    fn commits_only_after_archive_and_integrity_finish() {
650        let tar = [0; 1024];
651        let digest = Digest::from_bytes(Sha256::digest(tar).into());
652        let mut path = [0; 64];
653        let mut link = [0; 64];
654        let mut pax = [0; 64];
655        let archive = Archive::new(ArchiveBuffers {
656            path: &mut path,
657            link: &mut link,
658            pax: &mut pax,
659        });
660        let decoder = VerifiedDecoder::new(Decoder::tar(), digest, tar.len() as u64, digest);
661        let mut applier = LayerApplier::new(decoder, archive);
662        let mut sink = TransactionSink::default();
663        applier.push(&tar, &mut sink).unwrap();
664        assert!(sink.began);
665        assert!(!sink.committed);
666        applier.finish(&mut sink).unwrap();
667        assert!(sink.committed);
668        assert!(!sink.aborted);
669    }
670
671    #[test]
672    fn aborts_when_integrity_fails() {
673        let tar = [0; 1024];
674        let diff_id = Digest::from_bytes(Sha256::digest(tar).into());
675        let mut path = [0; 64];
676        let mut link = [0; 64];
677        let mut pax = [0; 64];
678        let archive = Archive::new(ArchiveBuffers {
679            path: &mut path,
680            link: &mut link,
681            pax: &mut pax,
682        });
683        let decoder = VerifiedDecoder::new(
684            Decoder::tar(),
685            Digest::from_bytes([1; 32]),
686            tar.len() as u64,
687            diff_id,
688        );
689        let mut applier = LayerApplier::new(decoder, archive);
690        let mut sink = TransactionSink::default();
691        applier.push(&tar, &mut sink).unwrap();
692        assert!(applier.finish(&mut sink).is_err());
693        assert!(sink.aborted);
694        assert!(!sink.committed);
695    }
696
697    #[cfg(feature = "gzip")]
698    #[test]
699    fn verifies_gzip_layers() {
700        const ENCODED: &[u8] = &[
701            0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xcb, 0x48, 0xcd, 0xc9,
702            0xc9, 0x07, 0x00, 0x86, 0xa6, 0x10, 0x36, 0x05, 0x00, 0x00, 0x00,
703        ];
704        let compressed = Digest::from_bytes(Sha256::digest(ENCODED).into());
705        let diff_id = Digest::from_bytes(Sha256::digest(b"hello").into());
706        let mut history = [0; gzip_zero::HISTORY_SIZE];
707        let decoder = Decoder::gzip(gzip_zero::DecoderBuffers {
708            history: &mut history,
709        })
710        .unwrap();
711        let mut decoder = VerifiedDecoder::new(decoder, compressed, ENCODED.len() as u64, diff_id);
712        let mut output = [0; 5];
713        let mut length = 0;
714        for byte in ENCODED {
715            decoder
716                .push(core::slice::from_ref(byte), |chunk| {
717                    output[length..length + chunk.len()].copy_from_slice(chunk);
718                    length += chunk.len();
719                    Ok::<_, ()>(())
720                })
721                .unwrap();
722        }
723        decoder.finish(|_| Ok::<_, ()>(())).unwrap();
724        assert_eq!(&output, b"hello");
725    }
726
727    #[cfg(feature = "zstd")]
728    #[test]
729    fn verifies_zstd_layers() {
730        const ENCODED: &[u8] = &[
731            0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0, 0, b'h', b'e', b'l', b'l', b'o',
732        ];
733        let compressed = Digest::from_bytes(Sha256::digest(ENCODED).into());
734        let diff_id = Digest::from_bytes(Sha256::digest(b"hello").into());
735        let mut history = [0; 5];
736        let mut block = [0; 5];
737        let mut literals = [0; 5];
738        let mut fse_scratch = [0i16; zstd_zero::FSE_SCRATCH_LEN];
739        let mut fse = [zstd_zero::FseEntry::new(); zstd_zero::FSE_ENTRIES];
740        let mut huffman = [zstd_zero::HuffmanEntry::new(); zstd_zero::HUFFMAN_ENTRIES];
741        let decoder = Decoder::zstd(zstd_zero::DecoderBuffers {
742            history: &mut history,
743            block: &mut block,
744            literals: &mut literals,
745            fse_scratch: &mut fse_scratch,
746            fse: &mut fse,
747            huffman: &mut huffman,
748        })
749        .unwrap();
750        let mut decoder = VerifiedDecoder::new(decoder, compressed, ENCODED.len() as u64, diff_id);
751        let mut output = [0; 5];
752        let mut length = 0;
753        decoder
754            .push(ENCODED, |chunk| {
755                output[length..length + chunk.len()].copy_from_slice(chunk);
756                length += chunk.len();
757                Ok::<_, ()>(())
758            })
759            .unwrap();
760        decoder.finish(|_| Ok::<_, ()>(())).unwrap();
761        assert_eq!(&output, b"hello");
762    }
763}