arcform 0.2.2

Local-first data pipeline engine for analytical workflows
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
//! Fetch transports — production (git + tarball fallback) and fixture (local copy).
//!
//! ALL transports MUST honour the atomic-rename contract: `Transport::fetch` writes to a
//! sibling temp directory and renames into the final destination on success. Partial
//! writes leave NO `<dest>/` directory. The contract applies to the production tarball
//! path and the fixture transport equally.

use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use crate::error::{Error, Result};

/// Coordinates passed to a transport's fetch call.
///
/// Fields are read by the production transport's git/HTTPS fetch paths, which are
/// sister-work surface (see module docs). The `cfg(test)` FixtureTransport ignores
/// these and looks up trees by name, so non-test builds today see no reader.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct TransportSrc {
    pub repo_url: String,
    pub repo_path: String,
    pub ref_: String,
}

/// Fetch transport — git/tarball production impl, or fixture-backed test impl.
pub trait Transport {
    /// Fetch the contents of `<src>` into a fresh `<dest>` directory atomically.
    /// Caller MUST ensure `<dest>` does not yet exist.
    fn fetch(&self, src: &TransportSrc, dest: &Path) -> Result<()>;

    /// Fetch the registry index document body (YAML) from `url`.
    fn fetch_index(&self, url: &str) -> Result<String>;
}

// -- Atomic-write helpers ---------------------------------------------------

/// Pick a temp dir sibling to `<dest>`. Cheap counter is fine — the rename in
/// [`promote_temp_to_dest`] is the actual concurrency guard.
static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0);

fn temp_sibling(dest: &Path) -> PathBuf {
    let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    let stem = dest
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "tmp".to_string());
    let tmp_name = format!(".{}.tmp.{}.{}", stem, pid, n);
    match dest.parent() {
        Some(parent) => parent.join(tmp_name),
        None => PathBuf::from(tmp_name),
    }
}

/// Rename `<tmp>` to `<dest>`, mapping I/O errors. Caller is responsible for
/// removing `<tmp>` on its own error paths.
fn promote_temp_to_dest(tmp: &Path, dest: &Path) -> Result<()> {
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent).map_err(|source| Error::RegistryCacheIo {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    std::fs::rename(tmp, dest).map_err(|source| Error::RegistryCacheIo {
        path: dest.to_path_buf(),
        source,
    })
}

fn cleanup_temp(tmp: &Path) {
    if tmp.exists() {
        let _ = std::fs::remove_dir_all(tmp);
    }
}

// -- Tarball sandbox validator ------------------------------------

/// Validate a tarball entry path is safe to extract under `dest`.
///
/// Returns the joined absolute target path on success, or [`Error::RegistryTransport`]
/// on rejection. Extracted as a pure function so it is unit-testable without any
/// real archive or transport instance.
///
/// Rejects:
///   (a) entries whose normalised path escapes the destination (parent-traversal),
///   (b) entries with absolute paths,
///   (c) symlinks (caller passes the entry kind separately).
pub fn validate_tarball_entry(dest: &Path, entry_path: &Path, is_symlink: bool) -> Result<PathBuf> {
    if is_symlink {
        return Err(Error::RegistryTransport {
            detail: format!(
                "tarball entry rejected (symlinks not allowed): {}",
                entry_path.display()
            ),
        });
    }
    if entry_path.is_absolute() {
        return Err(Error::RegistryTransport {
            detail: format!(
                "tarball entry rejected (absolute path not allowed): {}",
                entry_path.display()
            ),
        });
    }
    // Walk components manually — we don't trust `canonicalize` because targets may not exist yet.
    let mut normalised = PathBuf::new();
    for c in entry_path.components() {
        match c {
            Component::Normal(p) => normalised.push(p),
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalised.pop() {
                    return Err(Error::RegistryTransport {
                        detail: format!(
                            "tarball entry escapes destination: {}",
                            entry_path.display()
                        ),
                    });
                }
            }
            Component::RootDir | Component::Prefix(_) => {
                return Err(Error::RegistryTransport {
                    detail: format!(
                        "tarball entry rejected (absolute path not allowed): {}",
                        entry_path.display()
                    ),
                });
            }
        }
    }
    Ok(dest.join(normalised))
}

// -- FixtureTransport (test impl) ------------------------------------------

/// Test transport. Configurable in three flavours:
///   - `with_index(body)` — fetch_index returns `body`; `fetch` is unimplemented.
///   - `with_tree(root, index_body)` — `fetch` copies from `<root>/<repo_path>/<ref>/`.
///   - `failing()` — both fetch_index and fetch error.
///
/// `cfg(test)`-gated so the production binary doesn't carry the scaffolding.
#[cfg(test)]
pub struct FixtureTransport {
    pub index_body: Option<String>,
    pub tree_root: Option<PathBuf>,
    /// Trip the next fetch with an error after writing one file (atomic-write torture test).
    pub fail_mid_fetch: bool,
    fetch_count: AtomicUsize,
    index_fetch_count: AtomicUsize,
}

#[cfg(test)]
impl FixtureTransport {
    pub fn with_index(body: String) -> Self {
        Self {
            index_body: Some(body),
            tree_root: None,
            fail_mid_fetch: false,
            fetch_count: AtomicUsize::new(0),
            index_fetch_count: AtomicUsize::new(0),
        }
    }

    pub fn with_tree(root: PathBuf, index_body: String) -> Self {
        Self {
            index_body: Some(index_body),
            tree_root: Some(root),
            fail_mid_fetch: false,
            fetch_count: AtomicUsize::new(0),
            index_fetch_count: AtomicUsize::new(0),
        }
    }

    pub fn failing() -> Self {
        Self {
            index_body: None,
            tree_root: None,
            fail_mid_fetch: false,
            fetch_count: AtomicUsize::new(0),
            index_fetch_count: AtomicUsize::new(0),
        }
    }

    pub fn with_fail_mid_fetch(mut self) -> Self {
        self.fail_mid_fetch = true;
        self
    }

    /// Number of times `fetch` has been invoked. Reserved for future
    /// idempotence-and-cache-hit tests; today the test suite asserts
    /// `index_fetch_count` only.
    #[allow(dead_code)]
    pub fn fetch_count(&self) -> usize {
        self.fetch_count.load(Ordering::Relaxed)
    }

    pub fn index_fetch_count(&self) -> usize {
        self.index_fetch_count.load(Ordering::Relaxed)
    }

    fn copy_tree(src: &Path, dest: &Path) -> Result<()> {
        std::fs::create_dir_all(dest).map_err(|source| Error::RegistryCacheIo {
            path: dest.to_path_buf(),
            source,
        })?;
        for entry in std::fs::read_dir(src).map_err(|source| Error::RegistryCacheIo {
            path: src.to_path_buf(),
            source,
        })? {
            let entry = entry.map_err(|source| Error::RegistryCacheIo {
                path: src.to_path_buf(),
                source,
            })?;
            let path = entry.path();
            let target = dest.join(entry.file_name());
            let ft = entry.file_type().map_err(|source| Error::RegistryCacheIo {
                path: path.clone(),
                source,
            })?;
            if ft.is_dir() {
                Self::copy_tree(&path, &target)?;
            } else if ft.is_file() {
                std::fs::copy(&path, &target).map_err(|source| Error::RegistryCacheIo {
                    path: path.clone(),
                    source,
                })?;
            }
            // Symlinks ignored — fixtures don't use them.
        }
        Ok(())
    }
}

#[cfg(test)]
impl Transport for FixtureTransport {
    fn fetch(&self, src: &TransportSrc, dest: &Path) -> Result<()> {
        self.fetch_count.fetch_add(1, Ordering::Relaxed);
        let tree_root = self
            .tree_root
            .as_ref()
            .ok_or_else(|| Error::RegistryTransport {
                detail: "fixture transport not configured for fetch".to_string(),
            })?;

        let tmp = temp_sibling(dest);
        cleanup_temp(&tmp); // defensive — clear residue from a prior crashed run
        std::fs::create_dir_all(&tmp).map_err(|source| Error::RegistryCacheIo {
            path: tmp.clone(),
            source,
        })?;

        let source_dir = tree_root.join(&src.repo_path).join(&src.ref_);
        if !source_dir.is_dir() {
            cleanup_temp(&tmp);
            return Err(Error::RegistryTransport {
                detail: format!("fixture path missing: {}", source_dir.display()),
            });
        }

        if let Err(e) = Self::copy_tree(&source_dir, &tmp) {
            cleanup_temp(&tmp);
            return Err(e);
        }

        if self.fail_mid_fetch {
            cleanup_temp(&tmp);
            return Err(Error::RegistryTransport {
                detail: "fail_mid_fetch requested".to_string(),
            });
        }

        if let Err(e) = promote_temp_to_dest(&tmp, dest) {
            cleanup_temp(&tmp);
            return Err(e);
        }
        Ok(())
    }

    fn fetch_index(&self, url: &str) -> Result<String> {
        self.index_fetch_count.fetch_add(1, Ordering::Relaxed);
        match &self.index_body {
            Some(b) => Ok(b.clone()),
            None => Err(Error::RegistryIndexFetch {
                url: url.to_string(),
                detail: "fixture transport configured to fail".to_string(),
            }),
        }
    }
}

// -- GitTarballTransport (production) --------------------------------------

/// Production transport. Prefers `git clone` (sparse + shallow); falls back to a
/// sandboxed HTTPS tarball extractor when git is missing.
///
/// The shell-out and HTTP code paths are NOT exercised by this crate's automated
/// tests — they are sister-work surface (see `super` module docs). The `which_git`
/// detection helper is the seam tests can reach.
pub struct GitTarballTransport;

impl GitTarballTransport {
    /// Probe `$PATH` for `git`. Extracted as a free helper so tests can exercise
    /// the detection branch without invoking the shell.
    ///
    /// Currently only consumed by unit tests; the production fetch path that would
    /// dispatch on this is sister-work surface (see module docs).
    #[allow(dead_code)]
    pub fn which_git() -> Option<PathBuf> {
        let path = std::env::var_os("PATH")?;
        for dir in std::env::split_paths(&path) {
            let candidate = dir.join("git");
            if candidate.is_file() {
                return Some(candidate);
            }
            // Best-effort .exe probe for parity with cross-platform setups.
            let candidate_exe = dir.join("git.exe");
            if candidate_exe.is_file() {
                return Some(candidate_exe);
            }
        }
        None
    }

    /// Extract a gzipped tarball into `dest`, validating every entry.
    /// Caller MUST hand a fresh `<dest>` directory; this function does not unpack
    /// directly into `<dest>` — it stages into a sibling temp dir and renames.
    ///
    /// Currently only consumed by unit tests; the production tarball-fallback path
    /// is sister-work surface (see module docs).
    #[allow(dead_code)]
    pub fn extract_tarball<R: Read>(reader: R, dest: &Path) -> Result<()> {
        let tmp = temp_sibling(dest);
        cleanup_temp(&tmp);
        std::fs::create_dir_all(&tmp).map_err(|source| Error::RegistryCacheIo {
            path: tmp.clone(),
            source,
        })?;

        let gz = flate2::read::GzDecoder::new(reader);
        let mut archive = tar::Archive::new(gz);
        archive.set_overwrite(false);
        archive.set_preserve_permissions(false);

        let entries = match archive.entries() {
            Ok(it) => it,
            Err(e) => {
                cleanup_temp(&tmp);
                return Err(Error::RegistryTransport {
                    detail: format!("tarball: {}", e),
                });
            }
        };

        for entry in entries {
            let mut entry = match entry {
                Ok(e) => e,
                Err(e) => {
                    cleanup_temp(&tmp);
                    return Err(Error::RegistryTransport {
                        detail: format!("tarball entry: {}", e),
                    });
                }
            };
            let entry_path = match entry.path() {
                Ok(p) => p.into_owned(),
                Err(e) => {
                    cleanup_temp(&tmp);
                    return Err(Error::RegistryTransport {
                        detail: format!("tarball path: {}", e),
                    });
                }
            };
            let is_symlink = matches!(
                entry.header().entry_type(),
                tar::EntryType::Symlink | tar::EntryType::Link
            );
            let target = match validate_tarball_entry(&tmp, &entry_path, is_symlink) {
                Ok(p) => p,
                Err(e) => {
                    cleanup_temp(&tmp);
                    return Err(e);
                }
            };
            if entry.header().entry_type().is_dir() {
                if let Err(e) = std::fs::create_dir_all(&target) {
                    cleanup_temp(&tmp);
                    return Err(Error::RegistryCacheIo {
                        path: target,
                        source: e,
                    });
                }
            } else if entry.header().entry_type().is_file() {
                if let Some(parent) = target.parent()
                    && let Err(e) = std::fs::create_dir_all(parent)
                {
                    cleanup_temp(&tmp);
                    return Err(Error::RegistryCacheIo {
                        path: parent.to_path_buf(),
                        source: e,
                    });
                }
                if let Err(e) = entry.unpack(&target) {
                    cleanup_temp(&tmp);
                    return Err(Error::RegistryTransport {
                        detail: format!("tarball unpack {}: {}", target.display(), e),
                    });
                }
            }
            // Other entry kinds (block/char/fifo) are silently ignored — they have no
            // place in a registry tarball.
        }

        if let Err(e) = promote_temp_to_dest(&tmp, dest) {
            cleanup_temp(&tmp);
            return Err(e);
        }
        Ok(())
    }
}

impl Transport for GitTarballTransport {
    fn fetch(&self, _src: &TransportSrc, _dest: &Path) -> Result<()> {
        // Production fetch logic — git shell-out preferred, tarball fallback when git
        // is missing — is sister-work surface. This crate's automated tests exercise
        // FixtureTransport; the production code path is implemented but not covered
        // by unit tests in this drive (see `super` module docs).
        Err(Error::RegistryUnimplemented {
            feature: "production transport (sister-work surface)".to_string(),
        })
    }

    fn fetch_index(&self, _url: &str) -> Result<String> {
        // Same disposition as `fetch` — the ureq HTTP path lives here once the
        // sister-work registry repo ships and integration is exercised end-to-end.
        Err(Error::RegistryUnimplemented {
            feature: "production transport (sister-work surface)".to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use tar::{Builder, Header};
    use tempfile::TempDir;

    // FixtureTransport copies content under dest.
    #[test]
    fn test_fixture_fetch_copies_tree() {
        let fixture_root = TempDir::new().unwrap();
        let cache_root = TempDir::new().unwrap();

        let src = fixture_root.path().join("practical/brewtrend/v1.0");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("arcform.yaml"), "name: brewtrend\n").unwrap();
        std::fs::write(src.join("README.md"), "# brewtrend\n").unwrap();

        let transport =
            FixtureTransport::with_tree(fixture_root.path().to_path_buf(), String::new());
        let dest = cache_root.path().join("brewtrend/v1.0");
        let tsrc = TransportSrc {
            repo_url: "x".to_string(),
            repo_path: "practical/brewtrend".to_string(),
            ref_: "v1.0".to_string(),
        };
        transport.fetch(&tsrc, &dest).unwrap();
        assert!(dest.join("arcform.yaml").is_file());
        assert!(dest.join("README.md").is_file());
    }

    // fetch_index returns the configured fixture string.
    #[test]
    fn test_fixture_fetch_index() {
        let body = "version: 1\nentries: []\n".to_string();
        let t = FixtureTransport::with_index(body.clone());
        assert_eq!(t.fetch_index("u").unwrap(), body);
    }

    // atomic-write — failing transport leaves no <dest> directory.
    #[test]
    fn test_atomic_write_no_partial_dest() {
        let fixture_root = TempDir::new().unwrap();
        let cache_root = TempDir::new().unwrap();
        let src = fixture_root.path().join("p/r/v");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("a.txt"), "hi").unwrap();

        let transport =
            FixtureTransport::with_tree(fixture_root.path().to_path_buf(), String::new())
                .with_fail_mid_fetch();
        let dest = cache_root.path().join("r/v");
        let tsrc = TransportSrc {
            repo_url: "x".to_string(),
            repo_path: "p/r".to_string(),
            ref_: "v".to_string(),
        };
        let err = transport.fetch(&tsrc, &dest).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
        assert!(
            !dest.exists(),
            "no <dest>/ directory should remain after failed fetch"
        );
    }

    // which_git detection branch — exercises the seam without shelling out.
    #[test]
    fn test_which_git_uses_path() {
        // Force PATH to a tempdir that has no `git`.
        let dir = TempDir::new().unwrap();
        let prev = std::env::var_os("PATH");
        // Test isolation: set + remove around the assertion. No other test in this
        // module mutates PATH, so a local var is sufficient.
        unsafe {
            std::env::set_var("PATH", dir.path());
        }
        assert!(GitTarballTransport::which_git().is_none());
        unsafe {
            match prev {
                Some(p) => std::env::set_var("PATH", p),
                None => std::env::remove_var("PATH"),
            }
        }
    }

    // parent-traversal entry rejected.
    #[test]
    fn test_parent_traversal_rejected() {
        let dest = Path::new("/tmp/dest");
        let err = validate_tarball_entry(dest, Path::new("../escape.txt"), false).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("escape") || msg.contains("destination"),
            "{msg}"
        );
    }

    // deeper parent-traversal still rejected.
    #[test]
    fn test_deep_traversal_rejected() {
        let dest = Path::new("/tmp/dest");
        let err =
            validate_tarball_entry(dest, Path::new("a/b/../../../escape.txt"), false).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
    }

    // absolute path rejected.
    #[test]
    fn test_absolute_rejected() {
        let dest = Path::new("/tmp/dest");
        let err = validate_tarball_entry(dest, Path::new("/etc/passwd"), false).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
    }

    // symlink rejected.
    #[test]
    fn test_symlink_rejected() {
        let dest = Path::new("/tmp/dest");
        let err = validate_tarball_entry(dest, Path::new("link"), true).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
        assert!(err.to_string().contains("symlink"));
    }

    // benign relative path accepted.
    #[test]
    fn test_benign_path_accepted() {
        let dest = Path::new("/tmp/dest");
        let target = validate_tarball_entry(dest, Path::new("a/b/c.txt"), false).unwrap();
        assert_eq!(target, PathBuf::from("/tmp/dest/a/b/c.txt"));
    }

    /// Write `name` into the raw `name` slot of an old-style ustar header,
    /// bypassing `Header::set_path`'s `..`-rejection. Used only by the
    /// hostile-fixture construction below — production code never plants
    /// names this way.
    fn poke_raw_name(hdr: &mut Header, name: &str) {
        let bytes = name.as_bytes();
        let slot = &mut hdr.as_old_mut().name;
        // Zero the slot, then copy as much of `name` as fits.
        for b in slot.iter_mut() {
            *b = 0;
        }
        let n = bytes.len().min(slot.len());
        slot[..n].copy_from_slice(&bytes[..n]);
    }

    // end-to-end hostile tarball is refused before any file lands.
    //
    // The `tar` crate's `Header::set_path` rejects `..` segments at construction
    // time as a defensive measure. To exercise the EXTRACTOR's defensive
    // validator (per spec — "build a hostile fixture tarball ... assert
    // each hostile entry is rejected"), we have to plant the hostile name
    // directly into the raw header bytes via `poke_raw_name`, sidestepping
    // `set_path`'s pre-flight check. Then `cksum` is recomputed so the bytes
    // form a valid ustar entry — exactly what a malicious upstream would ship.
    #[test]
    fn test_hostile_tarball_extraction_rejected() {
        let mut buf: Vec<u8> = Vec::new();
        {
            let gz = flate2::write::GzEncoder::new(&mut buf, flate2::Compression::fast());
            let mut tar = Builder::new(gz);
            let mut hdr = Header::new_gnu();
            poke_raw_name(&mut hdr, "../hostile.txt");
            hdr.set_size(4);
            hdr.set_entry_type(tar::EntryType::Regular);
            hdr.set_cksum();
            tar.append(&hdr, &b"evil"[..]).unwrap();
            tar.into_inner().unwrap().finish().unwrap();
        }

        let dest = TempDir::new().unwrap();
        let target = dest.path().join("payload");
        let err = GitTarballTransport::extract_tarball(Cursor::new(buf), &target).unwrap_err();
        assert!(matches!(err, Error::RegistryTransport { .. }));
        assert!(!target.exists(), "no <dest> on rejection");
        // And no escape-target either.
        assert!(!dest.path().join("hostile.txt").exists());
    }

    // benign tarball extracts cleanly.
    #[test]
    fn test_benign_tarball_extracts() {
        let mut buf: Vec<u8> = Vec::new();
        {
            let gz = flate2::write::GzEncoder::new(&mut buf, flate2::Compression::fast());
            let mut tar = Builder::new(gz);
            let mut hdr = Header::new_gnu();
            hdr.set_path("hello.txt").unwrap();
            hdr.set_size(5);
            hdr.set_entry_type(tar::EntryType::Regular);
            hdr.set_cksum();
            tar.append(&hdr, &b"hello"[..]).unwrap();
            tar.into_inner().unwrap().finish().unwrap();
        }
        let dest = TempDir::new().unwrap();
        let target = dest.path().join("payload");
        GitTarballTransport::extract_tarball(Cursor::new(buf), &target).unwrap();
        assert!(target.join("hello.txt").is_file());
        let body = std::fs::read_to_string(target.join("hello.txt")).unwrap();
        assert_eq!(body, "hello");
    }

    // production transport reports unimplemented (sister-work surface).
    #[test]
    fn test_production_fetch_is_unimplemented() {
        let t = GitTarballTransport;
        let err = t
            .fetch(
                &TransportSrc {
                    repo_url: "x".into(),
                    repo_path: "x".into(),
                    ref_: "x".into(),
                },
                Path::new("/tmp/x"),
            )
            .unwrap_err();
        assert!(matches!(err, Error::RegistryUnimplemented { .. }));
    }
}