graphforge-cli 0.6.0

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

use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::Value;
use sha2::{Digest, Sha256};
use tempfile::TempDir;

#[path = "support/portable_package.rs"]
mod portable_package;
use portable_package::{
    Component, DeclaredFile, MANIFEST_PATH, controls, graph_parquet, hex, staged_entry_length,
    tar_header, write_large_package,
};

const GIB: u64 = 1024 * 1024 * 1024;
const MIB: u64 = 1024 * 1024;
const EVIDENCE_PATH: &str = "data/components/evidence/scan-0001/scan.bin";
const GRAPH_PATH: &str = "data/components/graph-data/graph-tree/topology/nodes.parquet";
const HUB_BUNDLE: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/fixtures/hub/generated/v1/objects/opendata-openalex.gfpb"
);
/// The evidence artifact: 5 GiB of zero bytes.
const EVIDENCE_LENGTH: u64 = 5 * GIB;
/// SHA-256 of [`EVIDENCE_LENGTH`] zero bytes:
/// `head -c $((5 * 1024 ** 3)) /dev/zero | sha256sum`.
const EVIDENCE_DIGEST: &str = "7f06c62352aebd8125b2a1841e2b9e1ffcbed602f381c3dcb3200200e383d1d5";
/// The memory the verifier may hold, whatever the package size.
/// The longest a run may take to feed and finish: generous over the seconds the
/// largest case takes, short of the CI job timeout.
const DEADLINE: Duration = Duration::from_secs(120);
const PEAK_RSS_LIMIT: u64 = 768 * MIB;
/// The graph Parquet entry of the staging run: more than
/// `max_parquet_walk_bytes` (64 MiB), so the walk stages it in scratch.
const GRAPH_ROWS: usize = 64;
const GRAPH_ROW_BYTES: usize = 1_150_000;

/// The limits a verifier runs under. `ulimit -f` counts 512-byte blocks in the
/// shell `sh` is here; the effective values are read back from
/// `/proc/<pid>/limits` and asserted, not trusted.
#[derive(Clone, Copy)]
struct Limits {
    address_space: u64,
    file_size: u64,
}

/// Virtual memory 1 GiB, files 64 MiB.
const OPAQUE: Limits = Limits {
    address_space: GIB,
    file_size: 64 * MIB,
};
/// The same memory; files 128 MiB, room for one staged graph entry.
const STAGED: Limits = Limits {
    address_space: GIB,
    file_size: 128 * MIB,
};

impl Limits {
    fn script(self) -> String {
        format!(
            "ulimit -v {}; ulimit -f {}; exec \"$0\" portable verify --input - --json",
            self.address_space / 1024,
            self.file_size / 512
        )
    }
}

fn gf_bin() -> PathBuf {
    std::fs::canonicalize(env!("CARGO_BIN_EXE_gf")).expect("resolve same-build gf binary")
}

/// One entry of a package under construction.
enum Body {
    Bytes(Vec<u8>),
    Zeros(u64),
}

impl Body {
    fn length(&self) -> u64 {
        match self {
            Body::Bytes(bytes) => bytes.len() as u64,
            Body::Zeros(length) => *length,
        }
    }
}

/// A component added to the fixture package: one file of `kind`.
struct Artifact {
    kind: &'static str,
    participant: &'static str,
    path: &'static str,
    media_type: &'static str,
    body: Body,
    /// SHA-256 of the file, as the manifest declares it.
    sha256: String,
}

/// The 5 GiB opaque artifact, with its pinned digest.
fn evidence(sha256: &str, body: Body) -> Artifact {
    Artifact {
        kind: "evidence",
        participant: "scan-0001",
        path: EVIDENCE_PATH,
        media_type: "application/octet-stream",
        body,
        sha256: sha256.into(),
    }
}

/// The fixture ontology-only package plus `artifacts`. Every control is
/// rebuilt to describe them, so the package is valid. `manifest` replaces the
/// semantic manifest bytes when given (an impostor), with the inventories
/// describing it. Returns the entries in canonical order and `package_digest`.
fn package(artifacts: Vec<Artifact>, manifest: Option<Vec<u8>>) -> (Vec<(String, Body)>, String) {
    let components: Vec<_> = artifacts
        .iter()
        .map(|artifact| Component {
            kind: artifact.kind,
            participant: artifact.participant,
            files: vec![DeclaredFile {
                path: artifact.path.to_owned(),
                media_type: artifact.media_type,
                length: artifact.body.length(),
                sha256: artifact.sha256.clone(),
            }],
        })
        .collect();
    let controls = controls(&components, manifest);
    let mut entries: Vec<_> = controls
        .entries
        .into_iter()
        .map(|(path, bytes)| (path, Body::Bytes(bytes)))
        .collect();
    entries.extend(
        artifacts
            .into_iter()
            .map(|artifact| (artifact.path.to_owned(), artifact.body)),
    );
    entries.sort_by(|left, right| left.0.cmp(&right.0));
    (entries, controls.package_digest)
}

/// A valid graph Parquet file of about 70 MiB, walked by the page profile.
fn large_graph_parquet() -> Vec<u8> {
    graph_parquet(GRAPH_ROWS, GRAPH_ROW_BYTES, "")
}

fn graph_data(file: Vec<u8>) -> Artifact {
    let sha256 = hex(&Sha256::digest(&file));
    Artifact {
        kind: "graph-data",
        participant: "graph-tree",
        path: GRAPH_PATH,
        media_type: "application/vnd.apache.parquet",
        body: Body::Bytes(file),
        sha256,
    }
}

/// A canonical bundle read one entry at a time: a zero-filled entry is
/// generated, never held. `limit` cuts the stream short.
struct Bundle {
    entries: std::vec::IntoIter<(String, Body)>,
    current: Vec<u8>,
    at: usize,
    zeros: u64,
    padding: usize,
    ended: bool,
    limit: u64,
}

impl Bundle {
    fn new(entries: Vec<(String, Body)>, limit: u64) -> Self {
        Self {
            entries: entries.into_iter(),
            current: Vec::new(),
            at: 0,
            zeros: 0,
            padding: 0,
            ended: false,
            limit,
        }
    }

    /// The stream's length, whole.
    fn length(entries: &[(String, Body)]) -> u64 {
        entries
            .iter()
            .map(|(_, body)| 512 + body.length().div_ceil(512) * 512)
            .sum::<u64>()
            + 1024
    }
}

impl Read for Bundle {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let room = buf
            .len()
            .min(usize::try_from(self.limit).unwrap_or(usize::MAX));
        let buf = &mut buf[..room];
        if buf.is_empty() {
            return Ok(0);
        }
        loop {
            let count = if self.at < self.current.len() {
                let count = buf.len().min(self.current.len() - self.at);
                buf[..count].copy_from_slice(&self.current[self.at..self.at + count]);
                self.at += count;
                count
            } else if self.zeros > 0 {
                let count = buf
                    .len()
                    .min(usize::try_from(self.zeros).unwrap_or(usize::MAX));
                buf[..count].fill(0);
                self.zeros -= count as u64;
                count
            } else if self.padding > 0 {
                let count = buf.len().min(self.padding);
                buf[..count].fill(0);
                self.padding -= count;
                count
            } else if let Some((path, body)) = self.entries.next() {
                self.current = tar_header(&path, body.length());
                self.at = 0;
                self.padding = (body.length().div_ceil(512) * 512 - body.length()) as usize;
                match body {
                    Body::Bytes(bytes) => self.current.extend(bytes),
                    Body::Zeros(length) => self.zeros = length,
                }
                continue;
            } else if !self.ended {
                self.ended = true;
                self.current = vec![0u8; 1024];
                self.at = 0;
                continue;
            } else {
                return Ok(0);
            };
            self.limit -= count as u64;
            return Ok(count);
        }
    }
}

/// The limits the child runs under, read from `/proc/<pid>/limits`.
struct Effective {
    address_space: u64,
    file_size: u64,
}

fn limit_field(text: &str, name: &str) -> Option<u64> {
    let line = text.lines().find(|line| line.starts_with(name))?;
    // "Max file size", soft, hard, "bytes".
    line.split_whitespace().nth(3)?.parse().ok()
}

/// Read the live child's effective limits. Until `sh` has `exec`ed `gf`, the
/// process is the shell, whose first argument is not the `gf` path; retry for
/// a bounded moment, then fail. Every read must succeed.
fn effective_limits(pid: u32) -> Result<Effective, String> {
    let give_up = Instant::now() + Duration::from_secs(10);
    let gf = gf_bin();
    loop {
        let read = |name: &str| std::fs::read_to_string(format!("/proc/{pid}/{name}"));
        if let (Ok(cmdline), Ok(limits)) = (read("cmdline"), read("limits"))
            && cmdline.split('\0').next() == gf.to_str()
        {
            return Ok(Effective {
                address_space: limit_field(&limits, "Max address space")
                    .ok_or("/proc limits: no address-space limit")?,
                file_size: limit_field(&limits, "Max file size")
                    .ok_or("/proc limits: no file-size limit")?,
            });
        }
        if Instant::now() >= give_up {
            return Err(format!("/proc/{pid}: gf never showed its command line"));
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// Peak resident memory of the largest reaped child, from `getrusage`. The
/// verifier is the only child the test process reaps (`exec` replaces the
/// shell), and nextest runs each test in its own process. The kernel keeps the
/// high-water mark over the whole life of the process, so the report built
/// after end of input is included.
fn children_max_rss() -> u64 {
    // SAFETY: `getrusage` only writes the zeroed `rusage` it is given.
    let (status, usage) = unsafe {
        let mut usage = std::mem::zeroed::<libc::rusage>();
        (libc::getrusage(libc::RUSAGE_CHILDREN, &mut usage), usage)
    };
    assert_eq!(status, 0, "getrusage failed");
    // `ru_maxrss` is in KiB on Linux.
    u64::try_from(usage.ru_maxrss).expect("non-negative") * 1024
}

struct Verified {
    code: Option<i32>,
    stdout: Vec<u8>,
    stderr: String,
    /// The limits the child ran under, when the run asked to read them.
    effective: Option<Effective>,
    /// Whole-life peak resident memory of the reaped child.
    max_rss: u64,
    fed: u64,
}

impl Verified {
    fn json(&self) -> Value {
        serde_json::from_slice(&self.stdout).unwrap_or_else(|error| {
            panic!("stdout is one JSON document ({error}): {}", self.stderr)
        })
    }

    /// The refusal: one JSON document on stderr, nothing on stdout.
    fn error(&self) -> Value {
        assert!(self.stdout.is_empty(), "a refusal prints no report");
        serde_json::from_str::<Value>(&self.stderr).unwrap_or_else(|error| {
            panic!("stderr is one JSON document ({error}): {}", self.stderr)
        })["error"]
            .clone()
    }

    /// The child ran under exactly `limits` and its peak resident memory over
    /// the whole run stayed under `PEAK_RSS_LIMIT`.
    fn assert_ran_within(&self, limits: Limits) {
        let effective = self
            .effective
            .as_ref()
            .expect("the run did not read the child's limits");
        assert_eq!(effective.address_space, limits.address_space);
        assert_eq!(effective.file_size, limits.file_size);
        println!("ru_maxrss_bytes={}", self.max_rss);
        assert!(self.max_rss > 0, "the child's peak memory was not recorded");
        assert!(
            self.max_rss < PEAK_RSS_LIMIT,
            "peak resident memory was {} bytes",
            self.max_rss
        );
    }
}

/// Whether a run reads the child's effective limits.
#[derive(Clone, Copy, PartialEq)]
enum Observe {
    No,
    Limits,
}

/// Run `gf portable verify --input - --json` on `stdin` under `limits`, with
/// `tmpdir` as its `TMPDIR`, feeding it from a thread. Feeding and completion
/// share one `DEADLINE`: on expiry the child is killed and reaped, the feeder
/// (which then gets `EPIPE`) is joined, and the test fails.
fn verify_stream(
    mut stdin: impl Read + Send + 'static,
    tmpdir: &Path,
    limits: Limits,
    observe: Observe,
) -> Verified {
    let started = Instant::now();
    let mut child = Command::new("sh")
        .args(["-c", &limits.script()])
        .arg(gf_bin())
        .env("TMPDIR", tmpdir)
        .current_dir(tmpdir)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn gf under ulimit");
    // The child is blocked reading the empty stdin until the feeder starts, so
    // it is alive for this read.
    let effective = (observe == Observe::Limits).then(|| {
        effective_limits(child.id()).unwrap_or_else(|error| {
            child.kill().ok();
            child.wait().ok();
            panic!("{error}")
        })
    });
    let mut pipe = child.stdin.take().unwrap();
    let feeder = std::thread::spawn(move || {
        let mut fed = 0u64;
        let mut block = vec![0u8; MIB as usize];
        loop {
            let count = stdin.read(&mut block).expect("generate the stream");
            // The verifier may refuse before the end of the stream.
            if count == 0 || pipe.write_all(&block[..count]).is_err() {
                return fed;
            }
            fed += count as u64;
        }
    });
    let mut stdout = child.stdout.take().unwrap();
    let mut stderr = child.stderr.take().unwrap();
    let out = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        stdout.read_to_end(&mut bytes).unwrap();
        bytes
    });
    let err = std::thread::spawn(move || {
        let mut text = String::new();
        stderr.read_to_string(&mut text).unwrap();
        text
    });
    let status = loop {
        if let Some(status) = child.try_wait().expect("poll gf") {
            break status;
        }
        if started.elapsed() >= DEADLINE {
            child.kill().expect("kill the stalled verifier");
            child.wait().expect("reap the stalled verifier");
            let fed = feeder.join().unwrap();
            let stderr = err.join().unwrap();
            panic!(
                "gf did not finish within {DEADLINE:?}; killed after {fed} bytes were fed: {stderr}"
            );
        }
        std::thread::sleep(Duration::from_millis(25));
    };
    Verified {
        code: status.code(),
        stdout: out.join().unwrap(),
        stderr: err.join().unwrap(),
        effective,
        max_rss: children_max_rss(),
        fed: feeder.join().unwrap(),
    }
}

fn assert_empty(dir: &Path) {
    let left: Vec<_> = std::fs::read_dir(dir)
        .unwrap()
        .map(|entry| entry.unwrap().file_name())
        .collect();
    assert!(left.is_empty(), "TMPDIR holds {left:?}");
}

fn zeros_digest(length: u64) -> String {
    let mut hash = Sha256::new();
    let block = vec![0u8; MIB as usize];
    let mut left = length;
    while left > 0 {
        let count = left.min(MIB);
        hash.update(&block[..count as usize]);
        left -= count;
    }
    hex(&hash.finalize())
}

fn bytes_by_kind(report: &Value) -> BTreeMap<String, u64> {
    report["bytes_by_kind"]
        .as_object()
        .unwrap()
        .iter()
        .map(|(kind, bytes)| (kind.clone(), bytes.as_u64().unwrap()))
        .collect()
}

/// A 5 GiB package verifies from stdin under a 1 GiB address space and a
/// 64 MiB file size: a verifier that buffered the input would fail to allocate,
/// and one that spooled it to a file would be killed at 64 MiB.
#[test]
fn a_five_gib_package_streams_from_stdin_in_bounded_memory() {
    let (entries, package_digest) = package(
        vec![evidence(EVIDENCE_DIGEST, Body::Zeros(EVIDENCE_LENGTH))],
        None,
    );
    let length = Bundle::length(&entries);
    assert!(length > 5 * GIB);
    let tmp = TempDir::new().unwrap();
    let run = verify_stream(
        Bundle::new(entries, u64::MAX),
        tmp.path(),
        OPAQUE,
        Observe::Limits,
    );

    run.assert_ran_within(OPAQUE);
    assert_eq!(run.code, Some(0), "{}", run.stderr);
    assert_eq!(run.fed, length, "the whole stream was read");
    let report = run.json();
    assert_eq!(report["integrity"], "verified");
    assert_eq!(report["source"], "stream");
    assert_eq!(report["package_digest"], format!("sha256:{package_digest}"));
    let kinds = bytes_by_kind(&report);
    assert_eq!(kinds["evidence"], EVIDENCE_LENGTH);
    assert_eq!(
        kinds.values().sum::<u64>(),
        report["payload_bytes"].as_u64().unwrap()
    );
    assert_empty(tmp.path());
}

/// A graph Parquet entry over `max_parquet_walk_bytes` verifies end to end in
/// the process, under a file size that holds one staged entry. How much it
/// writes is proven in-process, by the storage tests.
#[test]
fn a_graph_entry_over_the_walk_threshold_verifies_from_stdin() {
    let file = large_graph_parquet();
    let entry = file.len() as u64;
    assert!(
        entry > 64 * MIB,
        "{entry} bytes does not exceed the walk threshold"
    );
    let (entries, package_digest) = package(vec![graph_data(file)], None);
    let length = Bundle::length(&entries);
    let tmp = TempDir::new().unwrap();
    let run = verify_stream(
        Bundle::new(entries, u64::MAX),
        tmp.path(),
        STAGED,
        Observe::Limits,
    );

    run.assert_ran_within(STAGED);
    assert_eq!(run.code, Some(0), "{}", run.stderr);
    assert_eq!(run.fed, length);
    let report = run.json();
    assert_eq!(report["integrity"], "verified");
    assert_eq!(report["package_digest"], format!("sha256:{package_digest}"));
    assert_eq!(bytes_by_kind(&report)["graph-data"], entry);
    assert_eq!(report["plausibility"]["parquet"]["files_with_footer"], 1);
    assert_empty(tmp.path());
}

/// A stream cut short in the evidence artifact is refused as truncated.
#[test]
fn a_stream_truncated_at_sixty_percent_is_refused() {
    let (entries, _) = package(
        vec![evidence(EVIDENCE_DIGEST, Body::Zeros(EVIDENCE_LENGTH))],
        None,
    );
    let cut = Bundle::length(&entries) / 10 * 6;
    let tmp = TempDir::new().unwrap();
    let run = verify_stream(Bundle::new(entries, cut), tmp.path(), OPAQUE, Observe::No);

    assert_eq!(run.code, Some(2), "{}", run.stderr);
    let error = run.error();
    assert_eq!(error["code"], "GF_VALIDATION");
    assert!(
        error["diagnostics"][0]["message"]
            .as_str()
            .unwrap()
            .contains("truncated payload"),
        "{error}"
    );
    assert_empty(tmp.path());
}

/// A well-formed archive whose manifest is not one is refused, and so is one
/// whose artifact is not the bytes its manifest names.
#[test]
fn impostor_and_corrupted_bundles_are_refused() {
    let digest = zeros_digest(MIB);
    let impostor = package(
        vec![evidence(&digest, Body::Zeros(MIB))],
        Some(b"this is not a manifest".to_vec()),
    )
    .0;
    let corrupted = package(
        vec![evidence(
            &hex(&Sha256::digest(b"other bytes")),
            Body::Zeros(MIB),
        )],
        None,
    )
    .0;
    for entries in [impostor, corrupted] {
        let tmp = TempDir::new().unwrap();
        let run = verify_stream(
            Bundle::new(entries, u64::MAX),
            tmp.path(),
            OPAQUE,
            Observe::No,
        );
        assert_eq!(run.code, Some(2), "{}", run.stderr);
        assert_eq!(run.error()["code"], "GF_VALIDATION");
        assert_empty(tmp.path());
    }
}

/// A resource refusal keeps the CLI-wide exit code; its stable code is in the
/// JSON error.
#[test]
fn a_limit_refusal_reports_its_stable_code_in_json() {
    let (mut entries, _) = package(vec![evidence(&zeros_digest(MIB), Body::Zeros(MIB))], None);
    // A manifest beyond `max_manifest_bytes` (16 MiB), refused at its header.
    entries
        .iter_mut()
        .find(|(path, _)| path == MANIFEST_PATH)
        .unwrap()
        .1 = Body::Zeros(32 * MIB);
    let tmp = TempDir::new().unwrap();
    let run = verify_stream(
        Bundle::new(entries, u64::MAX),
        tmp.path(),
        OPAQUE,
        Observe::No,
    );
    assert_eq!(run.code, Some(1), "{}", run.stderr);
    assert_eq!(run.error()["code"], "GF_LIMIT_EXCEEDED");
    assert_empty(tmp.path());
}

struct Run {
    code: Option<i32>,
    stdout: Vec<u8>,
    stderr: String,
}

fn gf(args: &[&str], stdin: &[u8]) -> Run {
    let mut child = Command::new(gf_bin())
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn gf");
    let mut pipe = child.stdin.take().unwrap();
    let bytes = stdin.to_vec();
    let feeder = std::thread::spawn(move || {
        let _ = pipe.write_all(&bytes);
    });
    let output = child.wait_with_output().expect("run gf");
    feeder.join().unwrap();
    Run {
        code: output.status.code(),
        stdout: output.stdout,
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    }
}

fn one_document(text: &[u8]) -> Value {
    let mut documents = serde_json::Deserializer::from_slice(text).into_iter::<Value>();
    let document = documents.next().expect("a document").expect("valid JSON");
    assert!(documents.next().is_none(), "more than one document");
    document
}

/// The Hub fixture verifies alike from a file and from stdin, and `--json`
/// prints exactly one document either way.
#[test]
fn stdin_verifies_the_hub_bundle_with_one_json_document() {
    let bytes = std::fs::read(HUB_BUNDLE).unwrap();
    let stdin = gf(&["portable", "verify", "--input", "-", "--json"], &bytes);
    assert_eq!(stdin.code, Some(0), "{}", stdin.stderr);
    let mut stream = one_document(&stdin.stdout);
    let file = gf(
        &["portable", "verify", "--input", HUB_BUNDLE, "--json"],
        &[],
    );
    assert_eq!(file.code, Some(0), "{}", file.stderr);
    let mut file = one_document(&file.stdout);
    for report in [&mut file, &mut stream] {
        report.as_object_mut().unwrap().remove("source");
    }
    assert_eq!(file, stream);
}

#[test]
fn stdin_input_requires_full_mode() {
    let bytes = std::fs::read(HUB_BUNDLE).unwrap();
    let run = gf(
        &[
            "portable", "verify", "--input", "-", "--mode", "inspect", "--json",
        ],
        &bytes,
    );
    assert_eq!(run.code, Some(2));
    assert!(run.stdout.is_empty());
    assert_eq!(
        one_document(run.stderr.as_bytes())["error"]["code"],
        "GF_VALIDATION"
    );
}

/// `--url` is a stream too: a non-full mode is refused before any request.
#[test]
fn url_input_requires_full_mode() {
    let run = gf(
        &[
            "portable",
            "verify",
            "--url",
            "https://example.invalid/object",
            "--mode",
            "inspect",
            "--json",
        ],
        b"",
    );
    assert_eq!(run.code, Some(2));
    assert!(run.stdout.is_empty());
    let error = one_document(run.stderr.as_bytes());
    assert_eq!(error["error"]["code"], "GF_VALIDATION");
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("--mode full"),
        "{error}"
    );
}

/// A refused argument list is the one JSON error document the embedded
/// `execute` gives, with the argument-error exit code, on the real binary.
#[test]
fn an_argument_error_under_json_is_one_json_document() {
    for args in [
        &[
            "portable", "verify", "--input", "-", "--mode", "invalid", "--json",
        ][..],
        &["--json", "portable", "verify", "--no-such-flag"][..],
        &["--json", "no-such-command"][..],
    ] {
        let run = gf(args, &[]);
        assert_eq!(run.code, Some(2), "{args:?}: {}", run.stderr);
        assert!(run.stdout.is_empty(), "{args:?}");
        let error = &one_document(run.stderr.as_bytes())["error"];
        assert_eq!(error["code"], "GF_VALIDATION", "{args:?}");
        assert_eq!(error["details"]["source"], "argument_parser", "{args:?}");
    }
    // Without --json the refusal stays clap's text.
    let run = gf(&["portable", "verify", "--mode", "invalid"], &[]);
    assert_eq!(run.code, Some(2));
    assert!(run.stdout.is_empty());
    assert!(run.stderr.contains("invalid value"), "{}", run.stderr);
}

#[test]
fn help_and_version_print_normally() {
    for args in [
        &["--help"][..],
        &["--version"][..],
        &["portable", "verify", "--help"][..],
        &["--json", "--help"][..],
        &["--json", "--version"][..],
    ] {
        let run = gf(args, &[]);
        assert_eq!(run.code, Some(0), "{args:?}: {}", run.stderr);
        assert!(run.stderr.is_empty(), "{args:?}: {}", run.stderr);
        let text = String::from_utf8_lossy(&run.stdout);
        assert!(!text.trim().is_empty(), "{args:?}");
        assert!(
            serde_json::from_str::<Value>(&text).is_err(),
            "{args:?}: {text}"
        );
    }
}

/// The generated package reaches the requested size from its graph entries
/// alone, whatever the request, and verifies. The sizes straddle the first
/// walked file (`staged + 1`) and the 4 MiB the generator once reserved for
/// controls, which are far smaller.
#[test]
fn a_generated_package_is_never_short_of_the_requested_size() {
    let staged = staged_entry_length();
    for size in [
        staged - 1,
        staged,
        staged + 1,
        staged + 4 * MIB - 1,
        staged + 4 * MIB,
        staged + 4 * MIB + 1,
    ] {
        let mut bundle = Vec::new();
        let package = write_large_package(size, 7, &mut bundle, |_, _, _| {}).unwrap();
        assert_eq!(package.written, bundle.len() as u64);
        assert!(
            package.written >= size,
            "{size} requested, {} written",
            package.written
        );
        let run = gf(&["portable", "verify", "--input", "-", "--json"], &bundle);
        assert_eq!(run.code, Some(0), "{size}: {}", run.stderr);
        let report = one_document(&run.stdout);
        assert_eq!(report["integrity"], "verified", "{size}");
        assert_eq!(
            report["package_digest"],
            format!("sha256:{}", package.package_digest)
        );
    }
}