aither-sandbox 0.13.0

Terminal-first command execution with heel sandboxing
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
use std::io::{Cursor, Read};
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

use futures::{StreamExt, TryStreamExt, stream};
use futures_lite::io::AsyncReadExt;
use serde::{Deserialize, Serialize};
use url::Url;
use zenwave::Client;

use crate::tool_runtime::{
    DistributedTool, HostProgram, HostProgramPath, ImageTool, ImageTools, ManagedTool, ToolBinary,
    ToolBundle, ToolRuntimeError, ToolTarget, digest,
};

/// A kind of program a manifest artifact can provide.
trait Distributed: Copy + Send + Sync + Into<DistributedTool> {}

impl<P: Copy + Send + Sync + Into<DistributedTool>> Distributed for P {}

/// Largest xz decoder memory a trusted artifact may demand, in KiB.
const XZ_MEMORY_LIMIT_KIB: u32 = 256 * 1024;

/// Encoding of an artifact, with exactly one executable selected from archives.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "format", rename_all = "snake_case")]
pub enum ToolArtifactFormat {
    /// Uncompressed executable.
    Executable,
    /// Gzip-compressed tar archive.
    TarGzip {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
    /// Xz-compressed tar archive.
    TarXz {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
    /// Zip archive.
    Zip {
        /// Regular-file member containing the executable.
        executable: PathBuf,
    },
}

/// A remote artifact URL or a path relative to its packaged manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolArtifactLocation {
    /// A credential-free HTTPS URL or absolute local file URL.
    Download(Url),
    /// A portable artifact path beneath the manifest's installation directory.
    Bundled(PathBuf),
}

impl ToolArtifactLocation {
    const fn download_url(&self, tool: DistributedTool) -> Result<&Url, ToolRuntimeError> {
        match self {
            Self::Download(url) => Ok(url),
            Self::Bundled(_) => Err(ToolRuntimeError::ArtifactSource(tool)),
        }
    }
}

/// A version-pinned artifact from a trusted distribution manifest.
///
/// `P` is the kind of program it provides: a sandbox command
/// ([`ToolArtifact`]) or a host program ([`HostProgramArtifact`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PinnedArtifact<P> {
    /// Program provided by this artifact.
    pub tool: P,
    /// Semantic version of the program.
    pub version: String,
    /// Platform for which the executable was built.
    pub target: ToolTarget,
    /// Absolute local file URL or HTTPS distribution URL.
    pub url: ToolArtifactLocation,
    /// SHA-256 of the complete artifact, before extraction.
    pub sha256: String,
    /// Artifact encoding and executable member.
    pub encoding: ToolArtifactFormat,
}

/// A pinned artifact of a sandbox command.
pub type ToolArtifact = PinnedArtifact<ManagedTool>;

/// A pinned artifact of a host program.
///
/// Besides the archive digest it pins the digest of the executable inside, so
/// a prepared copy is verified without reading the archive.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostProgramArtifact {
    /// The pinned archive.
    #[serde(flatten)]
    pub artifact: PinnedArtifact<HostProgram>,
    /// SHA-256 of the extracted executable.
    pub executable_sha256: String,
}

/// Pinned artifact catalog used by every execution backend.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDistribution {
    artifacts: Vec<ToolArtifact>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    host_programs: Vec<HostProgramArtifact>,
}

impl ToolDistribution {
    /// Loads a trusted, version-pinned manifest.
    ///
    /// # Errors
    /// Rejects malformed manifests or unsupported source protocols.
    pub fn from_json(json: &[u8]) -> Result<Self, ToolRuntimeError> {
        let distribution: Self = serde_json::from_slice(json)?;
        distribution.validate()?;
        Ok(distribution)
    }

    /// Loads a packaged manifest and resolves contained artifacts before validation.
    ///
    /// # Errors
    /// Rejects unreadable manifests, escaping paths and invalid artifact metadata.
    pub async fn from_path(path: &Path) -> Result<Self, ToolRuntimeError> {
        let path = async_fs::canonicalize(path).await?;
        let root = path.parent().ok_or(ToolRuntimeError::InvalidArchive)?;
        let mut distribution: Self = serde_json::from_slice(&async_fs::read(&path).await?)?;
        for artifact in &mut distribution.artifacts {
            resolve_bundled(artifact, root)?;
        }
        for artifact in &mut distribution.host_programs {
            resolve_bundled(&mut artifact.artifact, root)?;
        }
        distribution.validate()?;
        Ok(distribution)
    }

    fn validate(&self) -> Result<(), ToolRuntimeError> {
        for artifact in &self.artifacts {
            validate_artifact(artifact)?;
        }
        for artifact in &self.host_programs {
            validate_artifact(&artifact.artifact)?;
            hex::decode_to_slice(&artifact.executable_sha256, &mut [0; 32])?;
        }
        Ok(())
    }

    /// Packages hash-verified executables and a relocatable manifest for installation.
    ///
    /// # Errors
    /// Fails on invalid artifacts, tampered existing content or manifest write failure.
    pub async fn package_into(&self, directory: &Path) -> Result<PathBuf, ToolRuntimeError> {
        self.validate()?;
        async_fs::create_dir_all(directory.join("artifacts")).await?;
        let (artifacts, host_programs) = futures::future::try_join(
            package_artifacts(&self.artifacts, directory, ManagedTool::ALL.len()),
            package_artifacts(
                &self
                    .host_programs
                    .iter()
                    .map(|program| program.artifact.clone())
                    .collect::<Vec<_>>(),
                directory,
                HostProgram::ALL.len(),
            ),
        )
        .await?;
        // Packaged artifacts are the bare executable, whose digest the
        // manifest pinned; packaging must have found exactly that.
        let host_programs = host_programs
            .into_iter()
            .map(|artifact| {
                if !self.host_programs.iter().any(|pinned| {
                    pinned.artifact.tool == artifact.tool
                        && pinned.artifact.target == artifact.target
                        && pinned.executable_sha256 == artifact.sha256
                }) {
                    return Err(ToolRuntimeError::Integrity {
                        tool: artifact.tool.into(),
                    });
                }
                Ok(HostProgramArtifact {
                    executable_sha256: artifact.sha256.clone(),
                    artifact,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        let manifest = directory.join("distribution.json");
        let content = serde_json::to_vec_pretty(&Self {
            artifacts,
            host_programs,
        })?;
        let destination = manifest.clone();
        let directory = directory.to_path_buf();
        blocking::unblock(move || {
            use std::io::Write;
            let mut stage = tempfile::NamedTempFile::new_in(directory)?;
            stage.write_all(&content)?;
            stage.persist(destination).map_err(|error| error.error)?;
            Ok::<(), ToolRuntimeError>(())
        })
        .await?;
        Ok(manifest)
    }

    /// The artifacts pinned for `target`, exactly one per managed tool.
    ///
    /// # Errors
    /// Rejects missing or duplicate tools for the target.
    fn select_artifacts(&self, target: &ToolTarget) -> Result<Vec<ToolArtifact>, ToolRuntimeError> {
        let selected = self
            .artifacts
            .iter()
            .filter(|artifact| &artifact.target == target)
            .cloned()
            .collect::<Vec<_>>();
        for tool in ManagedTool::ALL {
            match selected
                .iter()
                .filter(|artifact| artifact.tool == tool)
                .count()
            {
                0 => return Err(ToolRuntimeError::MissingTool(tool)),
                1 => {}
                _ => return Err(ToolRuntimeError::DuplicateTool(tool)),
            }
        }
        Ok(selected)
    }

    /// The tools a container image must carry for `target`, pinned without bytes.
    ///
    /// Never touches the network or the filesystem: each entry carries the
    /// command, the version it must report and the digest of its pinned
    /// archive, which is all the container backend needs to verify the image.
    ///
    /// # Errors
    /// Rejects missing or duplicate tools for the target, or a manifest pin
    /// whose version or digest is malformed.
    pub fn image_tools(&self, target: &ToolTarget) -> Result<ImageTools, ToolRuntimeError> {
        let tools = self
            .select_artifacts(target)?
            .into_iter()
            .map(|artifact| {
                let mut archive_sha256 = [0; 32];
                hex::decode_to_slice(&artifact.sha256, &mut archive_sha256)?;
                Ok(ImageTool {
                    tool: artifact.tool,
                    version: artifact.version.parse()?,
                    archive_sha256,
                })
            })
            .collect::<Result<Vec<_>, ToolRuntimeError>>()?;
        Ok(ImageTools::new(target.clone(), tools))
    }

    /// Stages the executables an image build must place at
    /// [`ImageTools::container_directory`]: `<out>/<image cache key>/bin`,
    /// returning that `<out>/<key>` directory.
    ///
    /// The bundle is downloaded and digest-verified through [`Self::load`]:
    /// downloads are expected on the image-build machine, never on the host
    /// that runs the container.
    ///
    /// # Errors
    /// Rejects missing/duplicate tools, failed downloads, oversized artifacts,
    /// digest mismatch or failed writes.
    ///
    /// # Panics
    /// Panics if the staged directory lacks its required parent.
    pub async fn stage_image_tools(
        &self,
        target: &ToolTarget,
        artifact_cache: &Path,
        out: &Path,
    ) -> Result<PathBuf, ToolRuntimeError> {
        let key = self.image_tools(target)?.cache_key()?;
        let bundle = self.load(target, artifact_cache).await?;
        let out = out.to_path_buf();
        blocking::unblock(move || {
            let prepared = bundle.prepare_local_sync(&out, &key)?;
            Ok(prepared
                .bin_dir()
                .parent()
                .expect("prepared binaries have a parent directory")
                .to_path_buf())
        })
        .await
    }

    /// Loads one complete target bundle concurrently, before shell execution.
    ///
    /// # Errors
    /// Rejects missing/duplicate tools, failed downloads, oversized artifacts,
    /// digest mismatch or unsafe/non-regular archive members.
    pub async fn load(
        &self,
        target: &ToolTarget,
        cache_root: &Path,
    ) -> Result<ToolBundle, ToolRuntimeError> {
        let selected = self.select_artifacts(target)?;
        async_fs::create_dir_all(cache_root).await?;
        let binaries = stream::iter(selected)
            .map(|artifact| {
                let cache_root = cache_root.to_path_buf();
                async move {
                    let bytes = load_artifact(&artifact, &cache_root).await?;
                    ToolBinary::verify(artifact.tool, &artifact.version, &digest(&bytes), bytes)
                }
            })
            .buffer_unordered(ManagedTool::ALL.len())
            .try_collect::<Vec<_>>()
            .await?;
        ToolBundle::new(target.clone(), binaries)
    }

    /// Prepares one host program for the host's platform and returns the path
    /// of its read-only executable, with the same pinning, download and
    /// verification as the sandbox commands.
    ///
    /// Archives are cached under `<cache_root>/artifacts` and executables
    /// under `<cache_root>/bin/<executable sha256>/<command>`. When that
    /// executable already exists with the pinned digest, the archive is not
    /// read. The path has no way into a [`ToolBundle`], so the program never
    /// reaches a sandbox `PATH` or the command catalog.
    ///
    /// # Errors
    /// Fails with [`ToolRuntimeError::MissingHostProgram`] naming the program
    /// and target when the distribution has no artifact for it,
    /// [`ToolRuntimeError::TargetMismatch`] when `target` is not the host's
    /// platform, [`ToolRuntimeError::Integrity`] when the extracted executable
    /// does not have the pinned digest, and on a failed download, archive
    /// digest mismatch, unsafe archive member or I/O failure.
    pub async fn prepare_host_program(
        &self,
        program: HostProgram,
        target: &ToolTarget,
        cache_root: &Path,
    ) -> Result<HostProgramPath, ToolRuntimeError> {
        let mut selected = self
            .host_programs
            .iter()
            .filter(|pinned| pinned.artifact.tool == program && &pinned.artifact.target == target);
        let (os, arch) = (target.os().to_owned(), target.arch().to_owned());
        let pinned = selected
            .next()
            .ok_or_else(|| ToolRuntimeError::MissingHostProgram {
                program,
                os: os.clone(),
                arch: arch.clone(),
            })?;
        if selected.next().is_some() {
            return Err(ToolRuntimeError::DuplicateHostProgram { program, os, arch });
        }
        if *target != ToolTarget::native()? {
            return Err(ToolRuntimeError::TargetMismatch);
        }
        let mut executable_sha256 = [0; 32];
        hex::decode_to_slice(&pinned.executable_sha256, &mut executable_sha256)?;
        let bin = cache_root.join("bin");
        let cached = {
            let (bin, target) = (bin.clone(), target.clone());
            blocking::unblock(move || {
                HostProgramPath::cached(&bin, program, &target, &executable_sha256)
            })
            .await?
        };
        if let Some(path) = cached {
            return Ok(path);
        }
        let artifacts = cache_root.join("artifacts");
        async_fs::create_dir_all(&artifacts).await?;
        let bytes = load_artifact(&pinned.artifact, &artifacts).await?;
        let target = target.clone();
        blocking::unblock(move || {
            if digest(&bytes) != executable_sha256 {
                return Err(ToolRuntimeError::Integrity {
                    tool: program.into(),
                });
            }
            HostProgramPath::write(&bin, program, &target, &executable_sha256, &bytes)
        })
        .await
    }
}

fn resolve_bundled<P: Distributed>(
    artifact: &mut PinnedArtifact<P>,
    root: &Path,
) -> Result<(), ToolRuntimeError> {
    if let ToolArtifactLocation::Bundled(relative) = &artifact.url {
        validate_member(relative)?;
        let url = Url::from_file_path(root.join(relative))
            .map_err(|()| ToolRuntimeError::ArtifactSource(artifact.tool.into()))?;
        artifact.url = ToolArtifactLocation::Download(url);
    }
    Ok(())
}

fn validate_artifact<P: Distributed>(artifact: &PinnedArtifact<P>) -> Result<(), ToolRuntimeError> {
    let tool = artifact.tool.into();
    let url = artifact.url.download_url(tool)?;
    match url.scheme() {
        "https" | "file" => {}
        _ => return Err(ToolRuntimeError::ArtifactSource(tool)),
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(ToolRuntimeError::ArtifactSource(tool));
    }
    hex::decode_to_slice(&artifact.sha256, &mut [0; 32])?;
    let _ = semver::Version::parse(&artifact.version)?;
    Ok(())
}

/// Stores every artifact's verified executable beside a relocatable manifest.
async fn package_artifacts<P: Distributed>(
    artifacts: &[PinnedArtifact<P>],
    directory: &Path,
    concurrency: usize,
) -> Result<Vec<PinnedArtifact<P>>, ToolRuntimeError> {
    stream::iter(artifacts.to_vec())
        .map(|mut artifact| {
            let directory = directory.to_path_buf();
            async move {
                let tool = artifact.tool.into();
                let bytes = load_artifact(&artifact, &directory.join("artifacts")).await?;
                let sha256 = digest(&bytes);
                let name = hex::encode(sha256);
                let path = directory.join(&name);
                blocking::unblock(move || {
                    use std::io::Write;
                    if path.try_exists()? {
                        if digest(&std::fs::read(&path)?) != sha256 {
                            return Err(ToolRuntimeError::Integrity { tool });
                        }
                    } else {
                        let mut stage = tempfile::NamedTempFile::new_in(&directory)?;
                        stage.write_all(&bytes)?;
                        match stage.persist_noclobber(&path) {
                            Ok(_) => {}
                            Err(error)
                                if error.error.kind() == std::io::ErrorKind::AlreadyExists =>
                            {
                                if digest(&std::fs::read(&path)?) != sha256 {
                                    return Err(ToolRuntimeError::Integrity { tool });
                                }
                            }
                            Err(error) => return Err(error.error.into()),
                        }
                    }
                    Ok::<(), ToolRuntimeError>(())
                })
                .await?;
                artifact.url = ToolArtifactLocation::Bundled(name.clone().into());
                artifact.sha256 = name;
                artifact.encoding = ToolArtifactFormat::Executable;
                Ok::<_, ToolRuntimeError>(artifact)
            }
        })
        .buffer_unordered(concurrency)
        .try_collect::<Vec<_>>()
        .await
}

/// Fetches an artifact through the cache and returns its extracted executable.
async fn load_artifact<P: Distributed>(
    artifact: &PinnedArtifact<P>,
    cache_root: &Path,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let tool = artifact.tool.into();
    let mut expected = [0; 32];
    hex::decode_to_slice(&artifact.sha256, &mut expected)?;
    let path = cache_root.join(hex::encode(expected));
    let encoded = match read_artifact_file(&path, tool).await {
        Ok(encoded) => encoded,
        Err(ToolRuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
            let encoded = download_artifact(tool, &artifact.url).await?;
            if digest(&encoded) != expected {
                return Err(ToolRuntimeError::Integrity { tool });
            }
            let destination = path.clone();
            let root = cache_root.to_path_buf();
            blocking::unblock(move || {
                use std::io::Write;
                let mut stage = tempfile::NamedTempFile::new_in(root)?;
                stage.write_all(&encoded)?;
                match stage.persist_noclobber(destination) {
                    Ok(_) => Ok::<(), ToolRuntimeError>(()),
                    Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
                    Err(error) => Err(error.error.into()),
                }
            })
            .await?;
            read_artifact_file(&path, tool).await?
        }
        Err(error) => return Err(error),
    };
    if digest(&encoded) != expected {
        return Err(ToolRuntimeError::Integrity { tool });
    }
    let encoding = artifact.encoding.clone();
    blocking::unblock(move || extract_executable(&encoding, &encoded)).await
}

async fn read_artifact_file(
    path: &Path,
    tool: DistributedTool,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let file = async_fs::File::open(path).await?;
    let mut bytes = Vec::new();
    file.take(64 * 1024 * 1024 + 1)
        .read_to_end(&mut bytes)
        .await?;
    if bytes.len() > 64 * 1024 * 1024 {
        return Err(ToolRuntimeError::ArtifactTooLarge(tool));
    }
    Ok(bytes)
}

async fn download_artifact(
    tool: DistributedTool,
    location: &ToolArtifactLocation,
) -> Result<Vec<u8>, ToolRuntimeError> {
    let url = location.download_url(tool)?;
    let encoded = match url.scheme() {
        "file" => {
            let path = url
                .to_file_path()
                .map_err(|()| ToolRuntimeError::ArtifactSource(tool))?;
            read_artifact_file(&path, tool).await?
        }
        "https" => {
            futures_lite::future::or(
                async {
                    let mut client = zenwave::client();
                    let response = client.get(url.as_str())?.await?;
                    if !response.status().is_success() {
                        return Err(ToolRuntimeError::DownloadStatus(response.status().as_u16()));
                    }
                    let mut bytes = Vec::new();
                    response
                        .into_body()
                        .into_reader()
                        .take(64 * 1024 * 1024 + 1)
                        .read_to_end(&mut bytes)
                        .await?;
                    Ok(bytes)
                },
                async {
                    async_io::Timer::after(Duration::from_secs(60)).await;
                    Err(ToolRuntimeError::Download(zenwave::Error::Timeout))
                },
            )
            .await?
        }
        _ => return Err(ToolRuntimeError::ArtifactSource(tool)),
    };
    if encoded.len() > 64 * 1024 * 1024 {
        return Err(ToolRuntimeError::ArtifactTooLarge(tool));
    }
    Ok(encoded)
}

fn read_executable(reader: impl Read) -> Result<Vec<u8>, ToolRuntimeError> {
    let mut bytes = Vec::new();
    reader.take(64 * 1024 * 1024 + 1).read_to_end(&mut bytes)?;
    if bytes.len() > 64 * 1024 * 1024 {
        return Err(ToolRuntimeError::InvalidArchive);
    }
    Ok(bytes)
}

fn validate_member(path: &Path) -> Result<(), ToolRuntimeError> {
    if path.as_os_str().is_empty()
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(ToolRuntimeError::InvalidArchive);
    }
    Ok(())
}

/// Reads the one regular member named `executable` from a decompressed tar stream.
fn select_tar_member(reader: impl Read, executable: &Path) -> Result<Vec<u8>, ToolRuntimeError> {
    let mut archive = tar::Archive::new(reader);
    let mut found = None;
    for entry in archive.entries()? {
        let entry = entry?;
        if entry.path()?.as_ref() != executable {
            continue;
        }
        if found.is_some() || !entry.header().entry_type().is_file() {
            return Err(ToolRuntimeError::InvalidArchive);
        }
        found = Some(read_executable(entry)?);
    }
    found.ok_or(ToolRuntimeError::InvalidArchive)
}

fn extract_executable(
    encoding: &ToolArtifactFormat,
    encoded: &[u8],
) -> Result<Vec<u8>, ToolRuntimeError> {
    match encoding {
        ToolArtifactFormat::Executable => Ok(encoded.to_vec()),
        ToolArtifactFormat::TarGzip { executable } => {
            validate_member(executable)?;
            select_tar_member(flate2::read::GzDecoder::new(encoded), executable)
        }
        ToolArtifactFormat::TarXz { executable } => {
            validate_member(executable)?;
            select_tar_member(
                lzma_rust2::XzReader::new_mem_limit(encoded, false, XZ_MEMORY_LIMIT_KIB),
                executable,
            )
        }
        ToolArtifactFormat::Zip { executable } => {
            validate_member(executable)?;
            let name = executable
                .to_str()
                .ok_or(ToolRuntimeError::InvalidArchive)?;
            let mut archive = zip::ZipArchive::new(Cursor::new(encoded))?;
            let mut found = None;
            for index in 0..archive.len() {
                let entry = archive.by_index(index)?;
                if entry.name()? != name {
                    continue;
                }
                if found.is_some() || !entry.is_file() || entry.is_symlink() {
                    return Err(ToolRuntimeError::InvalidArchive);
                }
                found = Some(read_executable(entry)?);
            }
            found.ok_or(ToolRuntimeError::InvalidArchive)
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;

    /// A script executable that reports `<command> <version>` to `--version`.
    pub fn script_tool(command: &str, version: &str) -> Vec<u8> {
        format!("#!/bin/sh\nprintf '%s\\n' '{command} {version}'\n").into_bytes()
    }

    /// A distribution pinning one `script_tool` executable per command for
    /// `target`, each artifact located by `url` — file URLs for a fixture that
    /// `load` can read, unreachable URLs where nothing may be downloaded.
    ///
    /// The files are written under `dir`; keep `dir` alive while `load` runs.
    pub fn script_distribution(
        target: &ToolTarget,
        version: &str,
        dir: &Path,
        url: impl Fn(&Path) -> ToolArtifactLocation,
    ) -> ToolDistribution {
        let artifacts = ManagedTool::ALL
            .into_iter()
            .map(|tool| {
                let bytes = script_tool(tool.command(), version);
                let path = dir.join(tool.command());
                std::fs::write(&path, &bytes).unwrap();
                ToolArtifact {
                    tool,
                    version: version.into(),
                    target: target.clone(),
                    url: url(&path),
                    sha256: hex::encode(digest(&bytes)),
                    encoding: ToolArtifactFormat::Executable,
                }
            })
            .collect();
        ToolDistribution {
            artifacts,
            host_programs: Vec::new(),
        }
    }

    /// File-backed artifacts for `script_distribution` fixtures that `load` reads.
    pub fn file_artifact(path: &Path) -> ToolArtifactLocation {
        ToolArtifactLocation::Download(Url::from_file_path(path).unwrap())
    }

    /// An artifact URL that can never be fetched, for fixtures that must
    /// prove nothing is downloaded.
    pub fn unreachable_artifact(_path: &Path) -> ToolArtifactLocation {
        ToolArtifactLocation::Download(Url::parse("http://127.0.0.1:9/tool").unwrap())
    }

    #[tokio::test]
    async fn stage_image_tools_produces_the_directory_layout_the_image_verifies() {
        let files = tempfile::tempdir().unwrap();
        let out = tempfile::tempdir().unwrap();
        let target = ToolTarget::native().unwrap();
        let distribution = script_distribution(&target, "1.0.0", files.path(), file_artifact);
        let staged = distribution
            .stage_image_tools(&target, &files.path().join("cache"), out.path())
            .await
            .unwrap();
        let image = distribution.image_tools(&target).unwrap();
        assert_eq!(
            staged,
            std::fs::canonicalize(out.path())
                .unwrap()
                .join(image.cache_key().unwrap())
        );
        for tool in ManagedTool::ALL {
            assert!(
                staged
                    .join("bin")
                    .join(tool.executable_name(&target))
                    .is_file()
            );
        }
    }

    #[tokio::test]
    async fn packaged_distribution_remains_valid_after_relocation() {
        let source = tempfile::tempdir().unwrap();
        let installation = tempfile::tempdir().unwrap();
        let relocated = tempfile::tempdir().unwrap();
        let bytes = b"verified artifact fixture";
        let binary = source.path().join("tool");
        async_fs::write(&binary, bytes).await.unwrap();
        let distribution = ToolDistribution {
            artifacts: ManagedTool::ALL
                .into_iter()
                .map(|tool| ToolArtifact {
                    tool,
                    version: "1.0.0".into(),
                    target: ToolTarget::native().unwrap(),
                    url: ToolArtifactLocation::Download(Url::from_file_path(&binary).unwrap()),
                    sha256: hex::encode(digest(bytes)),
                    encoding: ToolArtifactFormat::Executable,
                })
                .collect(),
            host_programs: Vec::new(),
        };
        let manifest = distribution
            .package_into(installation.path())
            .await
            .unwrap();
        async_fs::copy(&manifest, relocated.path().join("distribution.json"))
            .await
            .unwrap();
        let name = hex::encode(digest(bytes));
        async_fs::copy(
            installation.path().join(&name),
            relocated.path().join(&name),
        )
        .await
        .unwrap();
        let loaded = ToolDistribution::from_path(&relocated.path().join("distribution.json"))
            .await
            .unwrap();
        let bundle = loaded
            .load(&ToolTarget::native().unwrap(), &source.path().join("cache"))
            .await
            .unwrap();
        assert_eq!(
            bundle.catalog(),
            distribution
                .load(
                    &ToolTarget::native().unwrap(),
                    &source.path().join("original-cache")
                )
                .await
                .unwrap()
                .catalog()
        );
        async_fs::write(relocated.path().join(name), b"tampered")
            .await
            .unwrap();
        assert!(matches!(
            loaded
                .load(
                    &ToolTarget::native().unwrap(),
                    &source.path().join("fresh-cache")
                )
                .await,
            Err(ToolRuntimeError::Integrity { .. })
        ));
    }

    #[tokio::test]
    async fn bundled_artifacts_cannot_escape_the_installation() {
        let root = tempfile::tempdir().unwrap();
        let distribution = ToolDistribution {
            artifacts: vec![ToolArtifact {
                tool: ManagedTool::ApplyPatch,
                version: "1.0.0".into(),
                target: ToolTarget::native().unwrap(),
                url: ToolArtifactLocation::Bundled("../outside".into()),
                sha256: "00".repeat(32),
                encoding: ToolArtifactFormat::Executable,
            }],
            host_programs: Vec::new(),
        };
        let path = root.path().join("distribution.json");
        async_fs::write(&path, serde_json::to_vec(&distribution).unwrap())
            .await
            .unwrap();
        assert!(matches!(
            ToolDistribution::from_path(&path).await,
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    #[test]
    fn artifact_credentials_are_rejected_without_echoing_them() {
        let manifest = ToolDistribution {
            artifacts: vec![ToolArtifact {
                tool: ManagedTool::Ripgrep,
                version: "1.0.0".into(),
                target: ToolTarget::native().unwrap(),
                url: ToolArtifactLocation::Download(
                    Url::parse("https://user:secret@example.com/tool").unwrap(),
                ),
                sha256: "00".repeat(32),
                encoding: ToolArtifactFormat::Executable,
            }],
            host_programs: Vec::new(),
        };
        let error =
            ToolDistribution::from_json(&serde_json::to_vec(&manifest).unwrap()).unwrap_err();
        assert!(matches!(
            error,
            ToolRuntimeError::ArtifactSource(DistributedTool::Command(ManagedTool::Ripgrep))
        ));
        assert!(!error.to_string().contains("secret"));
    }

    #[test]
    fn rejects_path_traversal_before_archive_processing() {
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "../rg".into(),
        };
        assert!(matches!(
            extract_executable(&encoding, b""),
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    #[test]
    fn only_reads_the_regular_selected_member() {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(7);
        header.set_mode(0o755);
        header.set_cksum();
        tar.append_data(&mut header, "bin/rg", Cursor::new(b"content"))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        std::io::Write::write_all(&mut gzip, &contents).unwrap();
        let encoded = gzip.finish().unwrap();
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "bin/rg".into(),
        };
        assert_eq!(extract_executable(&encoding, &encoded).unwrap(), b"content");
    }

    #[test]
    fn rejects_symlink_members() {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_size(0);
        header.set_mode(0o755);
        header.set_link_name("/etc/passwd").unwrap();
        header.set_cksum();
        tar.append_data(&mut header, "rg", Cursor::new(b""))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        std::io::Write::write_all(&mut gzip, &contents).unwrap();
        let encoded = gzip.finish().unwrap();
        let encoding = ToolArtifactFormat::TarGzip {
            executable: "rg".into(),
        };
        assert!(matches!(
            extract_executable(&encoding, &encoded),
            Err(ToolRuntimeError::InvalidArchive)
        ));
    }

    fn tar_xz(member: &str, content: &[u8]) -> Vec<u8> {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(content.len() as u64);
        header.set_mode(0o755);
        header.set_cksum();
        tar.append_data(&mut header, member, Cursor::new(content))
            .unwrap();
        let contents = tar.into_inner().unwrap();
        let mut xz =
            lzma_rust2::XzWriter::new(Vec::new(), lzma_rust2::XzOptions::with_preset(1)).unwrap();
        std::io::Write::write_all(&mut xz, &contents).unwrap();
        xz.finish().unwrap()
    }

    #[test]
    fn extracts_the_executable_from_a_tar_xz_artifact() {
        let encoded = tar_xz("repo-search-x/search", b"daemon");
        let encoding = ToolArtifactFormat::TarXz {
            executable: "repo-search-x/search".into(),
        };
        assert_eq!(extract_executable(&encoding, &encoded).unwrap(), b"daemon");
        let missing = ToolArtifactFormat::TarXz {
            executable: "other".into(),
        };
        assert!(matches!(
            extract_executable(&missing, &encoded),
            Err(ToolRuntimeError::InvalidArchive)
        ));
        assert!(extract_executable(&encoding, b"not xz").is_err());
    }

    /// A distribution of fixture sandbox commands plus a tar.xz `search` host program.
    struct HostFixture {
        directory: tempfile::TempDir,
        distribution: ToolDistribution,
        executable: &'static [u8],
        archive: PathBuf,
    }

    impl HostFixture {
        async fn new() -> Self {
            let directory = tempfile::tempdir().unwrap();
            let target = ToolTarget::native().unwrap();
            let command = b"baseline command fixture";
            let command_path = directory.path().join("command");
            async_fs::write(&command_path, command).await.unwrap();
            let executable: &'static [u8] = b"host program fixture";
            let archive = directory.path().join("search.tar.xz");
            let encoded = tar_xz("repo-search/search", executable);
            async_fs::write(&archive, &encoded).await.unwrap();
            let distribution = ToolDistribution {
                artifacts: ManagedTool::ALL
                    .into_iter()
                    .map(|tool| ToolArtifact {
                        tool,
                        version: "1.0.0".into(),
                        target: target.clone(),
                        url: ToolArtifactLocation::Download(
                            Url::from_file_path(&command_path).unwrap(),
                        ),
                        sha256: hex::encode(digest(command)),
                        encoding: ToolArtifactFormat::Executable,
                    })
                    .collect(),
                host_programs: vec![HostProgramArtifact {
                    artifact: PinnedArtifact {
                        tool: HostProgram::RepoSearch,
                        version: "0.0.3".into(),
                        target,
                        url: ToolArtifactLocation::Download(Url::from_file_path(&archive).unwrap()),
                        sha256: hex::encode(digest(&encoded)),
                        encoding: ToolArtifactFormat::TarXz {
                            executable: "repo-search/search".into(),
                        },
                    },
                    executable_sha256: hex::encode(digest(executable)),
                }],
            };
            Self {
                directory,
                distribution,
                executable,
                archive,
            }
        }
    }

    #[tokio::test]
    async fn host_program_is_returned_as_a_host_path_and_never_enters_sandbox_tools() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let host = fixture.directory.path().join("host");
        let prepared = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &host)
            .await
            .unwrap();
        assert_eq!(std::fs::read(prepared.path()).unwrap(), fixture.executable);
        assert_eq!(
            prepared.path().file_name().unwrap(),
            HostProgram::RepoSearch.executable_name(&target).as_str()
        );
        // Preparing again reuses the verified copy.
        assert_eq!(
            fixture
                .distribution
                .prepare_host_program(HostProgram::RepoSearch, &target, &host)
                .await
                .unwrap(),
            prepared
        );

        let bundle = fixture.distribution.load(&target, &cache).await.unwrap();
        let without_host_programs = ToolDistribution {
            host_programs: Vec::new(),
            ..fixture.distribution.clone()
        };
        let baseline = without_host_programs
            .load(&target, &fixture.directory.path().join("baseline-cache"))
            .await
            .unwrap();
        assert_eq!(bundle.catalog(), baseline.catalog());
        assert_eq!(
            bundle.catalog().render().unwrap(),
            baseline.catalog().render().unwrap()
        );
        let local = bundle
            .prepare_local(&fixture.directory.path().join("local"))
            .await
            .unwrap();
        let staged = fixture
            .distribution
            .stage_image_tools(&target, &cache, &fixture.directory.path().join("container"))
            .await
            .unwrap();
        let staged_bin = staged.join("bin");
        for bin_dir in [local.bin_dir().clone(), staged_bin.clone()] {
            let names = std::fs::read_dir(&bin_dir)
                .unwrap()
                .map(|entry| entry.unwrap().file_name())
                .collect::<Vec<_>>();
            assert!(!names.iter().any(|name| name == "search"));
            assert!(!prepared.path().starts_with(&bin_dir));
        }
        assert!(
            !local
                .prepend_path(None)
                .unwrap()
                .to_string_lossy()
                .contains(prepared.path().parent().unwrap().to_str().unwrap())
        );
        assert!(!staged_bin.join("search").exists());
        assert!(!prepared.path().starts_with(&staged));
    }

    #[tokio::test]
    async fn tampered_host_program_artifact_is_rejected() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        async_fs::write(&fixture.archive, tar_xz("repo-search/search", b"tampered"))
            .await
            .unwrap();
        assert!(matches!(
            fixture
                .distribution
                .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
                .await,
            Err(ToolRuntimeError::Integrity {
                tool: DistributedTool::Host(HostProgram::RepoSearch)
            })
        ));
    }

    #[tokio::test]
    async fn pinned_executable_digest_mismatch_is_rejected() {
        let mut fixture = HostFixture::new().await;
        let pin = hex::encode(digest(b"another executable"));
        fixture.distribution.host_programs[0].executable_sha256 = pin.clone();
        let cache = fixture.directory.path().join("cache");
        assert!(matches!(
            fixture
                .distribution
                .prepare_host_program(
                    HostProgram::RepoSearch,
                    &ToolTarget::native().unwrap(),
                    &cache
                )
                .await,
            Err(ToolRuntimeError::Integrity {
                tool: DistributedTool::Host(HostProgram::RepoSearch)
            })
        ));
        assert!(!cache.join("bin").join(pin).exists());
    }

    #[tokio::test]
    async fn prepared_host_program_does_not_touch_the_archive() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let first = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        async_fs::remove_file(&fixture.archive).await.unwrap();
        async_fs::remove_dir_all(cache.join("artifacts"))
            .await
            .unwrap();
        let second = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        assert_eq!(first, second);
    }

    #[tokio::test]
    async fn tampered_cached_host_program_is_replaced_from_the_archive() {
        let fixture = HostFixture::new().await;
        let target = ToolTarget::native().unwrap();
        let cache = fixture.directory.path().join("cache");
        let prepared = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        let mut permissions = std::fs::metadata(prepared.path()).unwrap().permissions();
        #[allow(clippy::permissions_set_readonly_false)]
        permissions.set_readonly(false);
        std::fs::set_permissions(prepared.path(), permissions).unwrap();
        std::fs::write(prepared.path(), b"tampered").unwrap();
        let repaired = fixture
            .distribution
            .prepare_host_program(HostProgram::RepoSearch, &target, &cache)
            .await
            .unwrap();
        assert_eq!(repaired, prepared);
        assert_eq!(std::fs::read(repaired.path()).unwrap(), fixture.executable);
    }

    #[test]
    fn manifest_rejects_a_missing_or_malformed_executable_digest() {
        let manifest = |entry: &str| {
            format!(
                r#"{{"artifacts":[],"host_programs":[{{"tool":"repo_search","version":"0.0.3",
                "target":{{"os":"linux","arch":"x86_64"}},"url":"https://example.com/search.tar.xz",
                "sha256":"{}","encoding":{{"format":"executable"}}{entry}}}]}}"#,
                "0".repeat(64)
            )
        };
        assert!(ToolDistribution::from_json(manifest("").as_bytes()).is_err());
        for malformed in ["abc", &"g".repeat(64), &"0".repeat(63)] {
            let entry = format!(r#","executable_sha256":"{malformed}""#);
            assert!(ToolDistribution::from_json(manifest(&entry).as_bytes()).is_err());
        }
        let entry = format!(r#","executable_sha256":"{}""#, "0".repeat(64));
        ToolDistribution::from_json(manifest(&entry).as_bytes()).unwrap();
    }

    #[tokio::test]
    async fn host_program_without_an_artifact_for_the_target_names_both() {
        let fixture = HostFixture::new().await;
        let error = fixture
            .distribution
            .prepare_host_program(
                HostProgram::RepoSearch,
                &ToolTarget::from_probe("Windows_NT", "arm64").unwrap(),
                &fixture.directory.path().join("cache"),
            )
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            ToolRuntimeError::MissingHostProgram {
                program: HostProgram::RepoSearch,
                ..
            }
        ));
        assert_eq!(
            error.to_string(),
            "host program `search` has no artifact for windows/aarch64"
        );
    }

    #[test]
    fn third_party_manifest_pins_repo_search_for_its_published_targets() {
        let distribution =
            ToolDistribution::from_json(include_bytes!("../../patch/third-party-tools.json"))
                .unwrap();
        let mut targets = distribution
            .host_programs
            .iter()
            .map(|pinned| {
                assert_eq!(pinned.executable_sha256.len(), 64);
                let artifact = &pinned.artifact;
                assert_eq!(artifact.tool, HostProgram::RepoSearch);
                assert_eq!(artifact.version, "0.0.3");
                assert!(matches!(
                    artifact.encoding,
                    ToolArtifactFormat::TarXz { .. }
                ));
                (artifact.target.os(), artifact.target.arch())
            })
            .collect::<Vec<_>>();
        targets.sort_unstable();
        assert_eq!(
            targets,
            [
                ("linux", "aarch64"),
                ("linux", "x86_64"),
                ("macos", "aarch64")
            ]
        );
    }

    #[tokio::test]
    async fn packaged_distribution_keeps_host_programs() {
        let fixture = HostFixture::new().await;
        let installation = tempfile::tempdir().unwrap();
        let manifest = fixture
            .distribution
            .package_into(installation.path())
            .await
            .unwrap();
        let packaged = ToolDistribution::from_path(&manifest).await.unwrap();
        let prepared = packaged
            .prepare_host_program(
                HostProgram::RepoSearch,
                &ToolTarget::native().unwrap(),
                &fixture.directory.path().join("host"),
            )
            .await
            .unwrap();
        assert_eq!(std::fs::read(prepared.path()).unwrap(), fixture.executable);
    }
}