zlayer-registry 0.14.3

OCI container registry client with blob caching
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
//! OCI layer packing — the inverse of [`crate::unpack`].
//!
//! Bundles a set of files into a single `tar+zstd` layer whose bytes, when fed
//! back through [`crate::unpack::LayerUnpacker::unpack_layers`], restore the
//! files flat into the target directory. Used by the macOS VZ base-image builder
//! (`zlayer vz build-base`) to publish a Tart-style bundle (`disk.img`,
//! `hardware-model.bin`, `aux.img`) as an OCI artifact that the VZ runtime
//! (`crates/zlayer-agent/src/runtimes/macos_vz.rs`) can pull.
//!
//! The uncompressed tar is never fully materialized: `tar::Builder` streams each
//! entry straight into the zstd encoder, so peak memory is the zstd window plus
//! the final compressed buffer (which the registry push needs in memory anyway,
//! as `oci-client` 0.15 has no chunked blob upload).

use crate::unpack::media_types;
use std::io;
use std::path::Path;

/// Default zstd compression level for packed layers. Level 3 is the zstd default
/// — a good speed/ratio tradeoff for multi-gigabyte disk images.
pub const DEFAULT_ZSTD_LEVEL: i32 = 3;

/// Pack the named files (relative to `root`, stored under their given names) into
/// a single `tar+zstd` layer.
///
/// Each entry's header is derived from the on-disk file metadata. The returned
/// tuple is `(compressed_bytes, media_type)` ready to hand to a registry push as
/// an OCI layer; `media_type` is the standard
/// `application/vnd.oci.image.layer.v1.tar+zstd`.
///
/// # Errors
/// Returns an [`io::Error`] if any file cannot be opened/read or if the
/// tar/zstd streams fail to finalize.
pub fn pack_files_tar_zstd(
    root: &Path,
    files: &[&str],
    level: i32,
) -> io::Result<(Vec<u8>, String)> {
    let encoder = zstd::stream::write::Encoder::new(Vec::new(), level)?;
    let mut builder = tar::Builder::new(encoder);
    for name in files {
        let path = root.join(name);
        let mut f = std::fs::File::open(&path).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("open {} for packing: {e}", path.display()),
            )
        })?;
        builder
            .append_file(name, &mut f)
            .map_err(|e| io::Error::other(format!("append {} to layer: {e}", path.display())))?;
    }
    // `into_inner` writes the tar trailer and hands back the zstd encoder.
    let encoder = builder
        .into_inner()
        .map_err(|e| io::Error::other(format!("finalize tar: {e}")))?;
    let compressed = encoder
        .finish()
        .map_err(|e| io::Error::other(format!("finalize zstd: {e}")))?;
    Ok((compressed, media_types::TAR_ZSTD.to_string()))
}

/// Pack an entire directory tree rooted at `root` into a single `tar+zstd`
/// layer, preserving directories (including empty ones), regular-file mode
/// bits, and symlinks AS symlinks (relative and absolute targets stored
/// verbatim — toolchain trees are full of `opt/tool -> ../real` links that
/// must not be followed or materialized).
///
/// Any TOP-LEVEL entry whose name appears in `exclude_top` is skipped
/// entirely (used for `.build` / `.ready` stamps the caller re-creates on
/// unpack); the filter does NOT apply to nested entries of the same name.
///
/// Entries are named by their path relative to `root` with no leading `./`
/// (e.g. `opt/tool`), the same convention [`pack_files_tar_zstd`] uses and
/// [`crate::unpack::LayerUnpacker`] expects (its `is_safe_path` admits plain
/// relative components and joins them onto the rootfs). Directory listings are
/// sorted at every level and parents precede children, so packing the same
/// tree twice yields byte-identical output (stable digests).
///
/// The returned tuple is `(compressed_bytes, media_type)` ready to hand to a
/// registry push as an OCI layer; `media_type` is the standard
/// `application/vnd.oci.image.layer.v1.tar+zstd`.
///
/// # Errors
/// Returns an [`io::Error`] if the tree cannot be read (missing `root`,
/// unreadable entry, unsupported file type such as a socket) or if the
/// tar/zstd streams fail to finalize.
pub fn pack_dir_tar_zstd(
    root: &Path,
    exclude_top: &[&str],
    level: i32,
) -> io::Result<(Vec<u8>, String)> {
    let encoder = zstd::stream::write::Encoder::new(Vec::new(), level)?;
    let mut builder = tar::Builder::new(encoder);
    // Store symlinks as symlink entries. The builder default FOLLOWS links,
    // which would materialize each target's bytes under the link name.
    builder.follow_symlinks(false);

    for entry in sorted_dir_entries(root)? {
        let name = entry.file_name();
        if name.to_str().is_some_and(|n| exclude_top.contains(&n)) {
            continue;
        }
        append_tree(&mut builder, &entry.path(), Path::new(&name))?;
    }

    // `into_inner` writes the tar trailer and hands back the zstd encoder.
    let encoder = builder
        .into_inner()
        .map_err(|e| io::Error::other(format!("finalize tar: {e}")))?;
    let compressed = encoder
        .finish()
        .map_err(|e| io::Error::other(format!("finalize zstd: {e}")))?;
    Ok((compressed, media_types::TAR_ZSTD.to_string()))
}

/// Read a directory and return its entries sorted by file name, so the pack
/// order — and therefore the layer digest — is stable across runs.
fn sorted_dir_entries(dir: &Path) -> io::Result<Vec<std::fs::DirEntry>> {
    let mut entries = std::fs::read_dir(dir)
        .map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("read dir {} for packing: {e}", dir.display()),
            )
        })?
        .collect::<io::Result<Vec<_>>>()
        .map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("read dir entry in {} for packing: {e}", dir.display()),
            )
        })?;
    entries.sort_by_key(std::fs::DirEntry::file_name);
    Ok(entries)
}

/// Append one filesystem entry (and, for a directory, its sorted children,
/// depth-first with the parent first) to the tar under the relative name
/// `rel`. Uses `symlink_metadata` so a symlink — even one pointing at a
/// directory — is archived as a symlink entry, never descended into.
fn append_tree<W: io::Write>(
    builder: &mut tar::Builder<W>,
    path: &Path,
    rel: &Path,
) -> io::Result<()> {
    let meta = std::fs::symlink_metadata(path).map_err(|e| {
        io::Error::new(
            e.kind(),
            format!("stat {} for packing: {e}", path.display()),
        )
    })?;
    // `follow_symlinks(false)` on the builder makes this lstat internally too:
    // files/dirs/symlinks all get headers from on-disk metadata (mode bits
    // included), and a symlink entry carries its `read_link` target verbatim.
    builder
        .append_path_with_name(path, rel)
        .map_err(|e| io::Error::other(format!("append {} to layer: {e}", path.display())))?;
    if meta.is_dir() {
        for entry in sorted_dir_entries(path)? {
            let name = entry.file_name();
            append_tree(builder, &entry.path(), &rel.join(&name))?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unpack::LayerUnpacker;

    #[tokio::test]
    async fn pack_then_unpack_roundtrips_files_flat() {
        let src = tempfile::tempdir().unwrap();
        std::fs::write(src.path().join("disk.img"), b"DISK-CONTENT").unwrap();
        std::fs::write(src.path().join("hardware-model.bin"), b"HWMODEL").unwrap();
        std::fs::write(src.path().join("aux.img"), b"AUXDATA").unwrap();

        let (bytes, media_type) = pack_files_tar_zstd(
            src.path(),
            &["disk.img", "hardware-model.bin", "aux.img"],
            DEFAULT_ZSTD_LEVEL,
        )
        .unwrap();
        assert_eq!(media_type, media_types::TAR_ZSTD);
        assert!(!bytes.is_empty());

        let out = tempfile::tempdir().unwrap();
        let mut unpacker = LayerUnpacker::new(out.path().to_path_buf());
        unpacker
            .unpack_layers(&[(bytes, media_type)])
            .await
            .unwrap();

        assert_eq!(
            std::fs::read(out.path().join("disk.img")).unwrap(),
            b"DISK-CONTENT"
        );
        assert_eq!(
            std::fs::read(out.path().join("hardware-model.bin")).unwrap(),
            b"HWMODEL"
        );
        assert_eq!(
            std::fs::read(out.path().join("aux.img")).unwrap(),
            b"AUXDATA"
        );
    }

    #[test]
    fn missing_file_is_an_error() {
        let src = tempfile::tempdir().unwrap();
        let err = pack_files_tar_zstd(src.path(), &["nope.img"], DEFAULT_ZSTD_LEVEL).unwrap_err();
        assert!(err.to_string().contains("nope.img"));
    }

    /// Build the directory-pack fixture tree:
    ///
    /// ```text
    /// real                 regular file (target of the relative symlink)
    /// bin/runme            executable (0o755)
    /// nested/inner/data.txt
    /// nested/.ready        NOT top-level — must survive the top-level filter
    /// emptydir/            empty directory
    /// opt/tool -> ../real  relative symlink
    /// abslink -> /abs/target/file   absolute symlink
    /// .build/stamp         top-level excluded dir (with content)
    /// .ready               top-level excluded file
    /// ```
    #[cfg(unix)]
    fn build_fixture_tree(root: &std::path::Path) {
        use std::os::unix::fs::PermissionsExt;

        std::fs::write(root.join("real"), b"REAL-TOOL-BYTES").unwrap();

        std::fs::create_dir(root.join("bin")).unwrap();
        std::fs::write(root.join("bin/runme"), b"#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(
            root.join("bin/runme"),
            std::fs::Permissions::from_mode(0o755),
        )
        .unwrap();

        std::fs::create_dir_all(root.join("nested/inner")).unwrap();
        std::fs::write(root.join("nested/inner/data.txt"), b"nested-data").unwrap();
        std::fs::write(root.join("nested/.ready"), b"not-top-level").unwrap();

        std::fs::create_dir(root.join("emptydir")).unwrap();

        std::fs::create_dir(root.join("opt")).unwrap();
        std::os::unix::fs::symlink("../real", root.join("opt/tool")).unwrap();
        std::os::unix::fs::symlink("/abs/target/file", root.join("abslink")).unwrap();

        std::fs::create_dir(root.join(".build")).unwrap();
        std::fs::write(root.join(".build/stamp"), b"stamp").unwrap();
        std::fs::write(root.join(".ready"), b"ready").unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn pack_dir_then_unpack_roundtrips_tree() {
        use std::os::unix::fs::PermissionsExt;

        let src = tempfile::tempdir().unwrap();
        build_fixture_tree(src.path());

        let (bytes, media_type) =
            pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
        assert_eq!(media_type, media_types::TAR_ZSTD);
        assert!(!bytes.is_empty());

        let out = tempfile::tempdir().unwrap();
        let mut unpacker = LayerUnpacker::new(out.path().to_path_buf());
        unpacker
            .unpack_layers(&[(bytes, media_type)])
            .await
            .unwrap();

        // Regular files round-trip byte-identical.
        assert_eq!(
            std::fs::read(out.path().join("real")).unwrap(),
            b"REAL-TOOL-BYTES"
        );
        assert_eq!(
            std::fs::read(out.path().join("bin/runme")).unwrap(),
            b"#!/bin/sh\nexit 0\n"
        );
        assert_eq!(
            std::fs::read(out.path().join("nested/inner/data.txt")).unwrap(),
            b"nested-data"
        );

        // Executable mode bits preserved.
        let mode = std::fs::metadata(out.path().join("bin/runme"))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o755, "exec bits lost: {mode:o}");

        // Relative symlink preserved AS a symlink with an identical target.
        let tool = out.path().join("opt/tool");
        assert!(std::fs::symlink_metadata(&tool).unwrap().is_symlink());
        assert_eq!(
            std::fs::read_link(&tool).unwrap(),
            std::path::PathBuf::from("../real")
        );

        // Absolute symlink preserved AS a symlink. LayerUnpacker relativizes
        // absolute targets to keep the rootfs self-contained (unpack.rs
        // Symlink branch -> zlayer_paths::safe_fs::relativize_abs_symlink),
        // so a depth-0 link's `/abs/target/file` lands as `abs/target/file`.
        let abslink = out.path().join("abslink");
        assert!(std::fs::symlink_metadata(&abslink).unwrap().is_symlink());
        assert_eq!(
            std::fs::read_link(&abslink).unwrap(),
            std::path::PathBuf::from("abs/target/file")
        );

        // Excluded TOP-LEVEL entries are absent...
        assert!(!out.path().join(".build").exists());
        assert!(!out.path().join(".ready").exists());
        // ...but a nested entry with an excluded name survives.
        assert_eq!(
            std::fs::read(out.path().join("nested/.ready")).unwrap(),
            b"not-top-level"
        );

        // Empty directory round-trips.
        assert!(out.path().join("emptydir").is_dir());
    }

    /// The PACKED bytes must carry the absolute symlink target verbatim and
    /// name entries by root-relative path with no leading `./` — the
    /// relativization asserted in the round-trip test is the UNPACKER's doing.
    #[cfg(unix)]
    #[test]
    fn pack_dir_stores_verbatim_symlink_targets_and_relative_names() {
        use std::path::{Path, PathBuf};

        let src = tempfile::tempdir().unwrap();
        build_fixture_tree(src.path());

        let (bytes, _) =
            pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();

        let decoder = zstd::stream::read::Decoder::new(std::io::Cursor::new(&bytes[..])).unwrap();
        let mut archive = tar::Archive::new(decoder);
        let mut names: Vec<PathBuf> = Vec::new();
        let mut abs_target: Option<PathBuf> = None;
        let mut rel_target: Option<PathBuf> = None;
        for entry in archive.entries().unwrap() {
            let entry = entry.unwrap();
            let path = entry.path().unwrap().to_path_buf();
            assert!(
                !path.to_string_lossy().starts_with("./") && path.is_relative(),
                "entry not plain-relative: {}",
                path.display()
            );
            if path == Path::new("abslink") {
                assert_eq!(entry.header().entry_type(), tar::EntryType::Symlink);
                abs_target = entry.link_name().unwrap().map(|t| t.to_path_buf());
            }
            if path == Path::new("opt/tool") {
                assert_eq!(entry.header().entry_type(), tar::EntryType::Symlink);
                rel_target = entry.link_name().unwrap().map(|t| t.to_path_buf());
            }
            names.push(path);
        }

        assert_eq!(abs_target.unwrap(), PathBuf::from("/abs/target/file"));
        assert_eq!(rel_target.unwrap(), PathBuf::from("../real"));
        // Empty dir is an entry; excluded top-level names are not.
        assert!(names.contains(&PathBuf::from("emptydir")));
        assert!(!names.iter().any(|p| p.starts_with(".build")));
        assert!(!names.contains(&PathBuf::from(".ready")));
        // Exclusion is top-level only.
        assert!(names.contains(&PathBuf::from("nested/.ready")));
    }

    #[cfg(unix)]
    #[test]
    fn pack_dir_digest_is_deterministic() {
        use sha2::{Digest, Sha256};

        let src = tempfile::tempdir().unwrap();
        build_fixture_tree(src.path());

        let (first, _) =
            pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
        let (second, _) =
            pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();

        assert_eq!(
            hex::encode(Sha256::digest(&first)),
            hex::encode(Sha256::digest(&second)),
            "packing the same tree twice must yield an identical digest"
        );
        assert_eq!(first, second);
    }

    #[test]
    fn pack_dir_missing_root_is_an_error() {
        let src = tempfile::tempdir().unwrap();
        let missing = src.path().join("does-not-exist");
        let err = pack_dir_tar_zstd(&missing, &[], DEFAULT_ZSTD_LEVEL).unwrap_err();
        assert!(err.to_string().contains("does-not-exist"));
    }
}