packslip 1.11.2

A vendor-neutral signed release manifest: what shipped, and how to verify it
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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
//! Whole-artifact extraction into a destination-local, private staging tree.
//! No archive entry is trusted to choose an absolute path or permission mode.
use std::collections::BTreeMap;
use std::io::{Read, Seek, Write};
use std::path::{Path, PathBuf};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("archive I/O: {0}")]
    Io(#[from] std::io::Error),
    #[error("unsafe archive: {0}")]
    Unsafe(String),
    #[error("archive exceeds local extraction limits")]
    Limit,
    #[error("cannot extract artifact format {0:?}")]
    Format(String),
}
#[derive(Debug, Clone, Copy)]
pub struct Limits {
    pub bytes: u64,
    pub entries: u64,
}
impl Default for Limits {
    fn default() -> Self {
        Self {
            bytes: 10 * 1024 * 1024 * 1024,
            entries: 100_000,
        }
    }
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
    File,
    Dir,
    Symlink(String),
    Hardlink(String),
}
#[derive(Debug, Clone)]
struct Entry {
    path: PathBuf,
    kind: Kind,
    size: u64,
    executable: bool,
}

/// A stage and the exactly mapped declared commands. Holding the TempDir
/// removes an uncommitted stage on ordinary errors; the transaction keeps it.
pub struct Extracted {
    pub tree: tempfile::TempDir,
    pub bins: Vec<(String, PathBuf)>,
}

fn path(input: &str) -> Result<PathBuf, Error> {
    if input.len() > 4096
        || input.split('/').count() > 128
        || input.starts_with('/')
        || input.contains(['\\', ':', '\0'])
    {
        return Err(Error::Unsafe(format!("invalid path {input:?}")));
    }
    let mut result = PathBuf::new();
    for component in input.split('/').filter(|c| !c.is_empty() && *c != ".") {
        if component == ".." || component.ends_with([' ', '.']) {
            return Err(Error::Unsafe(format!("invalid path {input:?}")));
        }
        let base = component.split('.').next().unwrap().to_ascii_uppercase();
        if ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"].contains(&base.as_str())
            || base
                .strip_prefix("COM")
                .or_else(|| base.strip_prefix("LPT"))
                .is_some_and(|suffix| {
                    (suffix.len() == 1 && suffix.as_bytes()[0].is_ascii_digit())
                        || ["¹", "²", "³"].contains(&suffix)
                })
        {
            return Err(Error::Unsafe(format!("reserved path {input:?}")));
        }
        if component.to_ascii_lowercase().starts_with(".packslip") {
            return Err(Error::Unsafe(
                "archive uses a reserved ownership path".into(),
            ));
        }
        result.push(component);
    }
    if result.as_os_str().is_empty() {
        return Err(Error::Unsafe("empty archive path".into()));
    }
    Ok(result)
}
fn link_path(parent: &Path, target: &str) -> Result<PathBuf, Error> {
    if target.len() > 4096
        || target.split('/').count() > 128
        || target.starts_with('/')
        || target.contains(['\\', ':', '\0'])
    {
        return Err(Error::Unsafe(
            "absolute or platform-specific link target".into(),
        ));
    }
    let mut normalized = parent.to_path_buf();
    for part in target.split('/').filter(|p| !p.is_empty() && *p != ".") {
        if part == ".." {
            if !normalized.pop() {
                return Err(Error::Unsafe("link escapes extraction root".into()));
            }
        } else {
            normalized.push(path(part)?);
        }
    }
    if normalized.as_os_str().is_empty() {
        return Err(Error::Unsafe("link targets extraction root".into()));
    }
    Ok(normalized)
}
fn prefix(entries: &[Entry]) -> Option<PathBuf> {
    let first = entries.first()?.path.components().next()?;
    let base = PathBuf::from(first.as_os_str());
    let mut child = false;
    for entry in entries {
        if !entry.path.starts_with(&base) {
            return None;
        }
        if entry.path == base && entry.kind != Kind::Dir {
            return None;
        }
        child |= entry.path != base;
    }
    child.then_some(base)
}
fn mapped(input: &Path, strip: Option<&Path>) -> PathBuf {
    strip
        .and_then(|p| input.strip_prefix(p).ok())
        .unwrap_or(input)
        .to_path_buf()
}
fn validate(entries: &[Entry], limits: Limits, strip: Option<&Path>) -> Result<(), Error> {
    if entries.len() as u64 > limits.entries {
        return Err(Error::Limit);
    }
    let mut seen = BTreeMap::new();
    let mut total = 0u64;
    for entry in entries {
        total = total.checked_add(entry.size).ok_or(Error::Limit)?;
        if total > limits.bytes {
            return Err(Error::Limit);
        }
        let map = mapped(&entry.path, strip);
        if map.as_os_str().is_empty() {
            continue;
        }
        if seen
            .insert(
                PathBuf::from(
                    map.to_str()
                        .ok_or_else(|| Error::Unsafe("non-UTF8 mapped path".into()))?
                        .to_lowercase(),
                ),
                &entry.kind,
            )
            .is_some()
        {
            return Err(Error::Unsafe(format!(
                "duplicate mapped path {}",
                map.display()
            )));
        }
        match &entry.kind {
            Kind::Symlink(target) => {
                link_path(entry.path.parent().unwrap_or(Path::new("")), target)?;
                link_path(map.parent().unwrap_or(Path::new("")), target)?;
            }
            Kind::Hardlink(target) => {
                let target = path(target)?;
                let target = mapped(&target, strip);
                if target.as_os_str().is_empty() {
                    return Err(Error::Unsafe("hard link targets extraction root".into()));
                }
            }
            _ => {}
        }
    }
    for name in seen.keys() {
        for ancestor in name.ancestors().skip(1) {
            if let Some(kind) = seen.get(ancestor)
                && **kind != Kind::Dir
            {
                return Err(Error::Unsafe(
                    "archive entry has a non-directory ancestor".into(),
                ));
            }
        }
    }
    Ok(())
}
struct Bounded<'a, W: Write> {
    inner: &'a mut W,
    remaining: u64,
}
impl<W: Write> Write for Bounded<'_, W> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        if bytes.len() as u64 > self.remaining {
            return Err(std::io::Error::other("decompressed archive exceeds limit"));
        }
        let n = self.inner.write(bytes)?;
        self.remaining -= n as u64;
        Ok(n)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}
fn decoded(
    input: &Path,
    format: &str,
    parent: &Path,
    limit: u64,
) -> Result<tempfile::NamedTempFile, Error> {
    let mut spool = tempfile::NamedTempFile::new_in(parent)?;
    let mut writer = Bounded {
        inner: &mut spool,
        remaining: limit,
    };
    if crate::archive::compression_of(format) == Some("xz") {
        let mut reader = std::io::BufReader::new(std::fs::File::open(input)?);
        use std::io::BufRead as _;
        let mut stream = lzma_rust2::XzStream::new_mem_limit(true, 128 * 1024);
        let mut out = [0u8; 64 * 1024];
        loop {
            let input = reader.fill_buf()?;
            let eof = input.is_empty();
            let result = stream.process(
                input,
                &mut out,
                if eof {
                    lzma_rust2::Action::Finish
                } else {
                    lzma_rust2::Action::Run
                },
            )?;
            reader.consume(result.bytes_consumed);
            writer.write_all(&out[..result.bytes_produced])?;
            if result.status == lzma_rust2::Status::StreamEnd {
                break;
            }
            if result.bytes_consumed == 0 && result.bytes_produced == 0 {
                return Err(Error::Unsafe("truncated or stalled xz stream".into()));
            }
        }
    } else {
        let mut reader =
            crate::archive::decoder(input, format).map_err(|e| Error::Unsafe(e.to_string()))?;
        std::io::copy(&mut reader, &mut writer)?;
    }
    spool.as_file_mut().rewind()?;
    Ok(spool)
}
fn tar_entries(file: &mut std::fs::File, limits: Limits) -> Result<Vec<Entry>, Error> {
    file.rewind()?;
    {
        // The tar reader normally allocates GNU/PAX extension bodies before
        // yielding the entry. Inspect raw headers first to cap those allocations.
        let mut archive = tar::Archive::new(&mut *file);
        for (index, entry) in archive.entries()?.raw(true).enumerate() {
            if index as u64 >= limits.entries {
                return Err(Error::Limit);
            }
            let entry = entry?;
            let kind = entry.header().entry_type();
            if (kind.is_gnu_longname()
                || kind.is_gnu_longlink()
                || kind.is_pax_local_extensions()
                || kind.is_pax_global_extensions())
                && entry.size() > 16 * 1024
            {
                return Err(Error::Limit);
            }
        }
    }
    file.rewind()?;
    let mut archive = tar::Archive::new(file);
    let mut result = Vec::new();
    let mut size = 0u64;
    let mut count = 0u64;
    for entry in archive.entries()? {
        count += 1;
        if count > limits.entries {
            return Err(Error::Limit);
        }
        let entry = entry?;
        let p = entry.path()?;
        let p = p
            .to_str()
            .ok_or_else(|| Error::Unsafe("non-UTF8 archive path".into()))?;
        // Root directory placeholders are structural, not files.
        if (p == "." || p == "./") && entry.header().entry_type().is_dir() {
            continue;
        }
        let p = path(p)?;
        let kind = entry.header().entry_type();
        let link = || {
            let target = entry
                .link_name()?
                .ok_or_else(|| std::io::Error::other("invalid archive link"))?;
            let target = target
                .to_str()
                .ok_or_else(|| std::io::Error::other("non-UTF8 archive link"))?;
            if target.len() > 4096 || target.split('/').count() > 128 {
                return Err(std::io::Error::other("archive link exceeds path limits"));
            }
            Ok(target.to_owned())
        };
        let kind = if kind.is_file() {
            Kind::File
        } else if kind.is_dir() {
            Kind::Dir
        } else if kind.is_symlink() {
            Kind::Symlink(link()?)
        } else if kind.is_hard_link() {
            Kind::Hardlink(link()?)
        } else {
            return Err(Error::Unsafe("special archive entry".into()));
        };
        let bytes = match &kind {
            Kind::File => entry.size(),
            Kind::Symlink(target) | Kind::Hardlink(target) => target.len() as u64,
            _ => 0,
        };
        size = size.checked_add(bytes).ok_or(Error::Limit)?;
        if size > limits.bytes || result.len() as u64 >= limits.entries {
            return Err(Error::Limit);
        }
        result.push(Entry {
            path: p,
            kind,
            size: bytes,
            executable: entry.header().mode()? & 0o111 != 0,
        });
    }
    Ok(result)
}
/// A builder for a temporary directory only this user can write, whatever
/// the umask. Without explicit permissions, a user-private-group umask such as
/// Debian's 002 makes it group-writable, which the installer
/// refuses to install through.
pub(crate) fn private_builder(prefix: &str) -> tempfile::Builder<'_, 'static> {
    let mut builder = tempfile::Builder::new();
    builder.prefix(prefix);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        builder.permissions(std::fs::Permissions::from_mode(0o700));
    }
    builder
}

/// Create `path` and its missing parents as `rwxr-xr-x`, whatever the umask,
/// so an extracted tree is never group- or world-writable.
fn create_dirs(path: &Path) -> std::io::Result<()> {
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt as _;
        builder.mode(0o755);
    }
    builder.create(path)
}

fn output(root: &Path, relative: &Path) -> Result<std::fs::File, Error> {
    let out = root.join(relative);
    if let Some(parent) = out.parent() {
        create_dirs(parent)?;
    }
    Ok(std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(out)?)
}
fn mode(path: &Path, executable: bool) -> Result<(), Error> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(
            path,
            std::fs::Permissions::from_mode(if executable { 0o755 } else { 0o644 }),
        )?;
    }
    #[cfg(not(unix))]
    let _ = (path, executable);
    Ok(())
}
// Resolve existing symlinks without requiring the final target to exist.
// Preserve .. until after expanding links; normalizing first could hide an
// escape through a directory alias. Missing, still-confined targets are valid.
#[cfg(unix)]
fn resolved_link(root: &Path, relative: &Path) -> Result<PathBuf, Error> {
    use std::path::Component;
    let mut pending: std::collections::VecDeque<_> = relative
        .components()
        .map(|c| c.as_os_str().to_owned())
        .collect();
    let mut resolved = PathBuf::new();
    let mut expansions = 0;
    while let Some(component) = pending.pop_front() {
        match Path::new(&component).components().next() {
            Some(Component::CurDir) => continue,
            Some(Component::ParentDir) => {
                if !resolved.pop() {
                    return Err(Error::Unsafe(
                        "resolved link escapes extraction root".into(),
                    ));
                }
                continue;
            }
            Some(Component::Normal(_)) => resolved.push(&component),
            _ => return Err(Error::Unsafe("absolute link target".into())),
        }
        match std::fs::symlink_metadata(root.join(&resolved)) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                expansions += 1;
                if expansions > 128 {
                    return Err(Error::Unsafe("cyclic or excessively deep link".into()));
                }
                let target = std::fs::read_link(root.join(&resolved))?;
                resolved.pop();
                for component in target.components().rev() {
                    pending.push_front(component.as_os_str().to_owned());
                }
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    Ok(resolved)
}

#[cfg(unix)]
fn links(
    root: &Path,
    entries: &[Entry],
    strip: Option<&Path>,
    limits: Limits,
) -> Result<(), Error> {
    let _ = limits;
    let mut hard = BTreeMap::new();
    for entry in entries {
        let out = mapped(&entry.path, strip);
        if out.as_os_str().is_empty() {
            continue;
        }
        match &entry.kind {
            Kind::Symlink(target) => {
                let destination = root.join(&out);
                if let Some(parent) = destination.parent() {
                    create_dirs(parent)?;
                }
                #[cfg(unix)]
                std::os::unix::fs::symlink(target, destination)?;
            }
            Kind::Hardlink(target) => {
                hard.insert(out, mapped(&path(target)?, strip));
            }
            _ => {}
        }
    }
    for entry in entries
        .iter()
        .filter(|entry| matches!(entry.kind, Kind::Symlink(_)))
    {
        resolved_link(root, &mapped(&entry.path, strip))?;
    }
    // Resolve each dependency once. Retrying every uncreated hard link each
    // round makes a reverse-ordered chain quadratic in filesystem operations.
    let mut resolved: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
    for out in hard.keys() {
        let mut current = out.clone();
        let mut chain = Vec::new();
        let mut visited = std::collections::BTreeSet::new();
        let anchor = loop {
            if let Some(anchor) = resolved.get(&current) {
                break anchor.clone();
            }
            if !visited.insert(current.clone()) {
                return Err(Error::Unsafe("cyclic archive hard link".into()));
            }
            if let Some(target) = hard.get(&current) {
                chain.push(current);
                current = resolved_link(root, target)?;
            } else if root.join(&current).is_file() {
                break current;
            } else {
                return Err(Error::Unsafe("unresolved archive hard link".into()));
            }
        };
        for item in chain {
            resolved.insert(item, anchor.clone());
        }
    }
    for (out, anchor) in resolved {
        let destination = root.join(out);
        if let Some(parent) = destination.parent() {
            create_dirs(parent)?;
        }
        std::fs::hard_link(root.join(anchor), destination)?;
    }
    for entry in entries
        .iter()
        .filter(|entry| matches!(entry.kind, Kind::Symlink(_) | Kind::Hardlink(_)))
    {
        resolved_link(root, &mapped(&entry.path, strip))?;
    }
    Ok(())
}

#[cfg(not(unix))]
fn links(
    root: &Path,
    entries: &[Entry],
    strip: Option<&Path>,
    limits: Limits,
) -> Result<(), Error> {
    materialized_links(root, entries, strip, limits)
}

// Resolve the link graph to staged regular files before copying any link.
// Memoization makes long, reverse-ordered chains linear rather than repeatedly
// scanning the archive. No native Windows symlink privilege is required.
#[cfg(any(not(unix), test))]
fn materialized_links(
    root: &Path,
    entries: &[Entry],
    strip: Option<&Path>,
    limits: Limits,
) -> Result<(), Error> {
    let mut physical_size = entries
        .iter()
        .try_fold(0u64, |sum, e| sum.checked_add(e.size))
        .ok_or(Error::Limit)?;
    let fold = |path: &Path| -> Result<PathBuf, Error> {
        Ok(PathBuf::from(
            path.to_str()
                .ok_or_else(|| Error::Unsafe("non-UTF8 link path".into()))?
                .to_lowercase(),
        ))
    };
    let mut targets = BTreeMap::new();
    let mut files = BTreeMap::new();
    for entry in entries {
        let out = mapped(&entry.path, strip);
        let key = fold(&out)?;
        let target = match &entry.kind {
            Kind::Symlink(target) => link_path(out.parent().unwrap_or(Path::new("")), target)?,
            Kind::Hardlink(target) => mapped(&path(target)?, strip),
            Kind::File => {
                files.insert(key, out);
                continue;
            }
            _ => continue,
        };
        targets.insert(
            key,
            (out, fold(&target)?, matches!(entry.kind, Kind::Symlink(_))),
        );
    }
    // Resolve all links to the bytes to copy; then resolve hard-link inode
    // anchors separately, stopping at materialized symlinks. This preserves
    // h -> a when a is a copied symlink rather than linking h to a's source.
    fn resolve(
        targets: &BTreeMap<PathBuf, (PathBuf, PathBuf, bool)>,
        files: &BTreeMap<PathBuf, PathBuf>,
        stop_at_copy: bool,
    ) -> Result<BTreeMap<PathBuf, PathBuf>, Error> {
        let mut resolved: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
        for key in targets.keys() {
            let mut current = key.clone();
            let mut chain = Vec::new();
            let mut visited = std::collections::BTreeSet::new();
            let final_path = loop {
                if let Some(final_path) = resolved.get(&current) {
                    break final_path.clone();
                }
                if !visited.insert(current.clone()) {
                    return Err(Error::Unsafe("cyclic archive link".into()));
                }
                if let Some((out, target, is_copy)) = targets.get(&current) {
                    if stop_at_copy && *is_copy {
                        break out.clone();
                    }
                    chain.push(current);
                    current = target.clone();
                } else {
                    break files
                        .get(&current)
                        .ok_or_else(|| {
                            Error::Unsafe("Windows archive link is not a regular file".into())
                        })?
                        .clone();
                }
            };
            for item in chain {
                resolved.insert(item, final_path.clone());
            }
        }
        Ok(resolved)
    }
    let copied = resolve(&targets, &files, false)?;
    let anchors = resolve(&targets, &files, true)?;
    for (out, _, is_copy) in targets.values() {
        if !is_copy {
            continue;
        }
        let target = root.join(&copied[&fold(out)?]);
        physical_size = physical_size
            .checked_add(std::fs::metadata(&target)?.len())
            .ok_or(Error::Limit)?;
        if physical_size > limits.bytes {
            return Err(Error::Limit);
        }
        let destination = root.join(out);
        if let Some(parent) = destination.parent() {
            create_dirs(parent)?;
        }
        std::fs::copy(target, destination)?;
    }
    for (key, (out, _, is_copy)) in &targets {
        if *is_copy {
            continue;
        }
        let destination = root.join(out);
        if let Some(parent) = destination.parent() {
            create_dirs(parent)?;
        }
        std::fs::hard_link(root.join(&anchors[key]), destination)?;
    }
    Ok(())
}

/// Unpack every ordinary archive file beside the final destination, strip one
/// common enclosing directory, then validate only the declared command paths.
/// Never run a command or install a resource while extracting.
pub fn extract(
    input: &Path,
    artifact: &crate::Artifact,
    parent: &Path,
    limits: Limits,
) -> Result<Extracted, Error> {
    if limits.bytes == 0 || limits.entries == 0 {
        return Err(Error::Limit);
    }
    create_dirs(parent)?;
    let tree = private_builder(".packslip-stage-").tempdir_in(parent)?;
    let format = artifact
        .format
        .as_deref()
        .ok_or_else(|| Error::Format("absent".into()))?;
    let (entries, strip) = if format.starts_with("tar") || format == "tgz" {
        let spool_limit = limits
            .bytes
            .checked_add(limits.entries.saturating_mul(2048))
            .and_then(|n| n.checked_add(1024 * 1024))
            .ok_or(Error::Limit)?;
        let mut spool = decoded(input, format, parent, spool_limit)?;
        let entries = tar_entries(spool.as_file_mut(), limits)?;
        let strip = prefix(&entries);
        validate(&entries, limits, strip.as_deref())?;
        spool.as_file_mut().rewind()?;
        let mut archive = tar::Archive::new(spool.as_file_mut());
        for entry in archive.entries()? {
            let mut entry = entry?;
            let raw = entry.path()?.into_owned();
            let raw = raw
                .to_str()
                .ok_or_else(|| Error::Unsafe("non-UTF8 archive path".into()))?;
            if (raw == "." || raw == "./") && entry.header().entry_type().is_dir() {
                continue;
            }
            let relative = mapped(&path(raw)?, strip.as_deref());
            if relative.as_os_str().is_empty() {
                continue;
            }
            if entry.header().entry_type().is_dir() {
                create_dirs(&tree.path().join(&relative))?;
            } else if entry.header().entry_type().is_file() {
                let mut file = output(tree.path(), &relative)?;
                let n = std::io::copy(&mut entry, &mut file)?;
                if n != entry.size() {
                    return Err(Error::Unsafe("truncated archive file".into()));
                }
                file.sync_all()?;
                mode(
                    &tree.path().join(relative),
                    entry.header().mode()? & 0o111 != 0,
                )?;
            }
        }
        (entries, strip)
    } else if format == "zip" {
        let mut zip = zip::ZipArchive::new(std::fs::File::open(input)?)
            .map_err(|e| Error::Unsafe(e.to_string()))?;
        if zip.len() as u64 > limits.entries {
            return Err(Error::Limit);
        }
        let mut entries = Vec::new();
        let mut total = 0u64;
        for index in 0..zip.len() {
            let mut file = zip
                .by_index(index)
                .map_err(|e| Error::Unsafe(e.to_string()))?;
            // `create` reads `\` in a zip entry name as `/`, so extraction
            // does too; `path` still refuses `..\`, `\abs`, and `C:\` names.
            let file_path = path(&crate::archive::zip_path(
                &file.name().map_err(|e| Error::Unsafe(e.to_string()))?,
            ))?;
            let file_mode = file.unix_mode().unwrap_or(0o100644);
            let file_type = file_mode & 0o170000;
            let size = if file.is_dir() { 0 } else { file.size() };
            total = total.checked_add(size).ok_or(Error::Limit)?;
            if total > limits.bytes {
                return Err(Error::Limit);
            }
            let kind = if file.is_dir() {
                Kind::Dir
            } else if file_type == 0o120000 {
                if file.size() > 16384 {
                    return Err(Error::Limit);
                }
                let mut target = String::new();
                // One sentinel byte detects contents exceeding the declared size.
                file.by_ref()
                    .take(size.checked_add(1).ok_or(Error::Limit)?)
                    .read_to_string(&mut target)?;
                if target.len() as u64 != size {
                    return Err(Error::Unsafe("ZIP link size differs from directory".into()));
                }
                Kind::Symlink(target)
            } else if file_type == 0 || file_type == 0o100000 {
                Kind::File
            } else {
                return Err(Error::Unsafe("special ZIP entry".into()));
            };
            entries.push(Entry {
                path: file_path,
                kind,
                size,
                executable: file_mode & 0o111 != 0,
            });
        }
        let strip = prefix(&entries);
        validate(&entries, limits, strip.as_deref())?;
        for (index, entry) in entries.iter().enumerate() {
            let relative = mapped(&entry.path, strip.as_deref());
            if relative.as_os_str().is_empty() {
                continue;
            }
            match entry.kind {
                Kind::Dir => create_dirs(&tree.path().join(relative))?,
                Kind::File => {
                    let file = zip
                        .by_index(index)
                        .map_err(|e| Error::Unsafe(e.to_string()))?;
                    let mut out = output(tree.path(), &relative)?;
                    let n = std::io::copy(
                        &mut file.take(entry.size.checked_add(1).ok_or(Error::Limit)?),
                        &mut out,
                    )?;
                    if n != entry.size {
                        return Err(Error::Unsafe("ZIP size differs from directory".into()));
                    }
                    out.sync_all()?;
                    mode(&tree.path().join(relative), entry.executable)?;
                }
                _ => {}
            }
        }
        (entries, strip)
    } else if ["raw", "gz", "xz", "zst", "bz2"].contains(&format) {
        let name = artifact
            .name
            .strip_suffix(&format!(
                ".{}",
                crate::archive::compression_of(format).unwrap_or("")
            ))
            .unwrap_or(&artifact.name);
        let name = path(name)?;
        let mut decoded = decoded(input, format, parent, limits.bytes)?;
        let mut out = output(tree.path(), &name)?;
        std::io::copy(decoded.as_file_mut(), &mut out)?;
        out.sync_all()?;
        mode(&tree.path().join(name), true)?;
        (vec![], None)
    } else {
        return Err(Error::Format(format.into()));
    };
    links(tree.path(), &entries, strip.as_deref(), limits)?;
    let mut bins = Vec::new();
    let canonical = tree.path().canonicalize()?;
    for bin in &artifact.bin {
        let raw = path(&bin.path)?;
        let mapped = mapped(&raw, strip.as_deref());
        let target = tree.path().join(&mapped).canonicalize()?;
        if !target.starts_with(&canonical) || !target.is_file() {
            return Err(Error::Unsafe(
                "declared command is not a file within the stage".into(),
            ));
        }
        path(&bin.name)?;
        if bin.name.contains('/') {
            return Err(Error::Unsafe("command name contains a path".into()));
        }
        mode(&target, true)?;
        bins.push((bin.name.clone(), mapped));
    }
    if bins.is_empty() {
        return Err(Error::Unsafe("artifact declares no commands".into()));
    }
    Ok(Extracted { tree, bins })
}

#[cfg(test)]
mod tests {
    use super::*;
    fn artifact(name: &str, format: &str, bins: Vec<crate::Bin>) -> crate::Artifact {
        serde_json::from_value(serde_json::json!({"name":name,"url":"https://example.invalid/tool","size":1,"format":format,"bin":bins})).unwrap()
    }
    fn tar_file(parent: &Path, entries: &[(&str, &[u8])]) -> PathBuf {
        let path = parent.join("archive.tar");
        let mut archive = tar::Builder::new(std::fs::File::create(&path).unwrap());
        for (name, bytes) in entries {
            let mut header = tar::Header::new_gnu();
            header.set_size(bytes.len() as u64);
            header.set_mode(0o4755);
            header.set_cksum();
            archive.append_data(&mut header, name, *bytes).unwrap();
        }
        archive.finish().unwrap();
        path
    }
    #[test]
    fn full_tree_strips_one_directory_and_keeps_runtime_off_path() {
        let parent = tempfile::tempdir().unwrap();
        let input = tar_file(
            parent.path(),
            &[("pkg/bin/tool", b"tool"), ("pkg/lib/runtime", b"runtime")],
        );
        let extracted = extract(
            &input,
            &artifact("archive.tar", "tar", vec![crate::Bin::new("pkg/bin/tool")]),
            parent.path(),
            Limits::default(),
        )
        .unwrap();
        assert_eq!(
            extracted.bins,
            vec![("tool".into(), PathBuf::from("bin/tool"))]
        );
        assert_eq!(
            std::fs::read(extracted.tree.path().join("lib/runtime")).unwrap(),
            b"runtime"
        );
        assert!(!extracted.tree.path().join("pkg").exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                std::fs::metadata(extracted.tree.path().join("bin/tool"))
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o7777,
                0o755
            );
        }
    }
    #[test]
    fn paths_limits_special_entries_and_duplicates_fail() {
        for name in [
            "../escape",
            "/escape",
            "C:/escape",
            "x\\escape",
            "dir/NUL",
            "dir/conin$",
            "dir/CONOUT$.txt",
            "dir/com¹.txt",
            "dir/LPT²",
            "dir/COM³",
            "dir/tool.",
            ".packslip-owner.json",
        ] {
            assert!(path(name).is_err(), "{name}");
        }
        let parent = tempfile::tempdir().unwrap();
        let input = tar_file(parent.path(), &[("tool", b"too large")]);
        assert!(
            extract(
                &input,
                &artifact("archive.tar", "tar", vec![crate::Bin::new("tool")]),
                parent.path(),
                Limits {
                    bytes: 2,
                    entries: 100
                }
            )
            .is_err()
        );
        let input = tar_file(parent.path(), &[("tool", b"a"), ("Tool", b"b")]);
        assert!(
            extract(
                &input,
                &artifact("archive.tar", "tar", vec![crate::Bin::new("tool")]),
                parent.path(),
                Limits::default()
            )
            .is_err()
        );
        assert!(
            extract(
                &input,
                &artifact("archive.tar", "tar", vec![crate::Bin::new("tool")]),
                parent.path(),
                Limits {
                    bytes: 100,
                    entries: 1
                }
            )
            .is_err()
        );
        let mut archive = tar::Builder::new(std::fs::File::create(&input).unwrap());
        let mut header = tar::Header::new_gnu();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Fifo);
        header.set_mode(0o644);
        header.set_cksum();
        archive
            .append_data(&mut header, "fifo", std::io::empty())
            .unwrap();
        archive.finish().unwrap();
        assert!(
            extract(
                &input,
                &artifact("archive.tar", "tar", vec![crate::Bin::new("fifo")]),
                parent.path(),
                Limits::default()
            )
            .is_err()
        );
    }
    #[test]
    fn tar_extension_allocations_and_link_targets_are_bounded() {
        let parent = tempfile::tempdir().unwrap();
        for kind in [
            tar::EntryType::GNULongLink,
            tar::EntryType::GNULongName,
            tar::EntryType::XHeader,
        ] {
            let input = parent.path().join("extension.tar");
            let mut builder = tar::Builder::new(std::fs::File::create(&input).unwrap());
            let mut header = tar::Header::new_gnu();
            header.set_entry_type(kind);
            header.set_size(16 * 1024 + 1);
            header.set_mode(0o644);
            header.set_cksum();
            builder
                .append_data(
                    &mut header,
                    "metadata",
                    vec![b'a'; 16 * 1024 + 1].as_slice(),
                )
                .unwrap();
            builder.finish().unwrap();
            let mut file = std::fs::File::open(&input).unwrap();
            assert!(matches!(
                tar_entries(&mut file, Limits::default()),
                Err(Error::Limit)
            ));
        }
        for target in ["a/".repeat(129), "a".repeat(4097)] {
            assert!(link_path(Path::new(""), &target).is_err());
            let input = parent.path().join("long-link.tar");
            let mut builder = tar::Builder::new(std::fs::File::create(&input).unwrap());
            let mut header = tar::Header::new_gnu();
            header.set_entry_type(tar::EntryType::Symlink);
            header.set_size(0);
            header.set_mode(0o777);
            builder.append_link(&mut header, "link", &target).unwrap();
            builder.finish().unwrap();
            let mut file = std::fs::File::open(&input).unwrap();
            assert!(tar_entries(&mut file, Limits::default()).is_err());
        }
        let input = parent.path().join("link.tar");
        let mut builder = tar::Builder::new(std::fs::File::create(&input).unwrap());
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_size(0);
        header.set_mode(0o777);
        builder
            .append_link(&mut header, "optional", "runtime")
            .unwrap();
        builder.finish().unwrap();
        let mut file = std::fs::File::open(&input).unwrap();
        assert!(matches!(
            tar_entries(
                &mut file,
                Limits {
                    bytes: 6,
                    entries: 100
                }
            ),
            Err(Error::Limit)
        ));
        assert_eq!(
            tar_entries(
                &mut file,
                Limits {
                    bytes: 7,
                    entries: 100
                }
            )
            .unwrap()[0]
                .size,
            7
        );
    }
    #[test]
    fn links_are_checked_before_and_after_stripping() {
        let entries = vec![Entry {
            path: PathBuf::from("pkg/link"),
            kind: Kind::Symlink("../escape".into()),
            size: 0,
            executable: false,
        }];
        assert!(validate(&entries, Limits::default(), Some(Path::new("pkg"))).is_err());
        let entries = vec![
            Entry {
                path: PathBuf::from("pkg/link"),
                kind: Kind::Symlink("target".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: PathBuf::from("pkg/link/child"),
                kind: Kind::File,
                size: 1,
                executable: true,
            },
        ];
        assert!(validate(&entries, Limits::default(), Some(Path::new("pkg"))).is_err());
    }
    #[test]
    fn zip_and_compressed_bare_executables_are_supported() {
        let parent = tempfile::tempdir().unwrap();
        let input = parent.path().join("tool.zip");
        let mut zip = zip::ZipWriter::new(std::fs::File::create(&input).unwrap());
        zip.start_file("pkg/tool.exe", zip::write::SimpleFileOptions::default())
            .unwrap();
        zip.write_all(b"tool").unwrap();
        zip.start_file("pkg/runtime.dll", zip::write::SimpleFileOptions::default())
            .unwrap();
        zip.write_all(b"runtime").unwrap();
        zip.finish().unwrap();
        let extracted = extract(
            &input,
            &artifact("tool.zip", "zip", vec![crate::Bin::new("pkg/tool.exe")]),
            parent.path(),
            Limits::default(),
        )
        .unwrap();
        assert!(extracted.tree.path().join("runtime.dll").is_file());
        let input = parent.path().join("tool.gz");
        let mut gzip = flate2::write::GzEncoder::new(
            std::fs::File::create(&input).unwrap(),
            flate2::Compression::default(),
        );
        gzip.write_all(b"tool").unwrap();
        gzip.finish().unwrap();
        let extracted = extract(
            &input,
            &artifact("tool.gz", "gz", vec![crate::Bin::new("tool")]),
            parent.path(),
            Limits::default(),
        )
        .unwrap();
        assert_eq!(
            std::fs::read(extracted.tree.path().join("tool")).unwrap(),
            b"tool"
        );
        assert!(
            extract(
                &input,
                &artifact("tool.gz", "gz", vec![crate::Bin::new("tool")]),
                parent.path(),
                Limits {
                    bytes: 2,
                    entries: 100
                }
            )
            .is_err()
        );
    }
    #[test]
    fn zip_entries_may_separate_directories_with_backslashes() {
        let parent = tempfile::tempdir().unwrap();
        let zip_of = |names: &[&str]| {
            let input = parent.path().join("tool.zip");
            let mut zip = zip::ZipWriter::new(std::fs::File::create(&input).unwrap());
            for name in names {
                zip.start_file(*name, zip::write::SimpleFileOptions::default())
                    .unwrap();
                zip.write_all(name.as_bytes()).unwrap();
            }
            zip.finish().unwrap();
            input
        };
        let tool = || artifact("tool.zip", "zip", vec![crate::Bin::new("pkg/bin/tool.exe")]);
        let input = zip_of(&["pkg\\bin\\tool.exe", "pkg\\lib\\runtime.dll"]);
        let extracted = extract(&input, &tool(), parent.path(), Limits::default()).unwrap();
        assert_eq!(
            extracted.bins,
            vec![("tool".into(), PathBuf::from("bin/tool.exe"))]
        );
        assert!(extracted.tree.path().join("lib/runtime.dll").is_file());
        for escape in [
            "..\\escape",
            "pkg\\..\\..\\escape",
            "\\escape",
            "C:\\escape",
        ] {
            let input = zip_of(&["pkg\\bin\\tool.exe", escape]);
            assert!(
                matches!(
                    extract(&input, &tool(), parent.path(), Limits::default()),
                    Err(Error::Unsafe(_))
                ),
                "{escape}"
            );
        }
    }
    #[test]
    fn zip_link_targets_count_toward_aggregate_bytes_before_retention() {
        let parent = tempfile::tempdir().unwrap();
        let input = parent.path().join("links.zip");
        let mut zip = zip::ZipWriter::new(std::fs::File::create(&input).unwrap());
        zip.start_file("pkg/tool", zip::write::SimpleFileOptions::default())
            .unwrap();
        zip.write_all(b"x").unwrap();
        zip.add_symlink("pkg/a", "tool", zip::write::SimpleFileOptions::default())
            .unwrap();
        zip.add_symlink("pkg/b", "tool", zip::write::SimpleFileOptions::default())
            .unwrap();
        zip.finish().unwrap();
        assert!(matches!(
            extract(
                &input,
                &artifact("links.zip", "zip", vec![crate::Bin::new("pkg/tool")]),
                parent.path(),
                Limits {
                    bytes: 5,
                    entries: 100
                }
            ),
            Err(Error::Limit)
        ));
    }
    #[test]
    fn windows_file_link_graph_is_independent_of_archive_order_and_bounded() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("file"), b"file").unwrap();
        let entries = vec![
            Entry {
                path: "a".into(),
                kind: Kind::Symlink("b".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "b".into(),
                kind: Kind::Symlink("c".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "c".into(),
                kind: Kind::Hardlink("file".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "file".into(),
                kind: Kind::File,
                size: 4,
                executable: false,
            },
        ];
        materialized_links(
            root.path(),
            &entries,
            None,
            Limits {
                bytes: 12,
                entries: 100,
            },
        )
        .unwrap();
        assert_eq!(std::fs::read(root.path().join("a")).unwrap(), b"file");
        assert_eq!(std::fs::read(root.path().join("b")).unwrap(), b"file");
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("file"), b"file").unwrap();
        assert!(matches!(
            materialized_links(
                root.path(),
                &entries,
                None,
                Limits {
                    bytes: 11,
                    entries: 100
                }
            ),
            Err(Error::Limit)
        ));
        let cyclic = vec![
            entries[0].clone(),
            Entry {
                path: "b".into(),
                kind: Kind::Symlink("a".into()),
                size: 0,
                executable: false,
            },
        ];
        assert!(materialized_links(root.path(), &cyclic, None, Limits::default()).is_err());
        let overflowing = vec![
            Entry {
                size: u64::MAX,
                ..entries[3].clone()
            },
            entries[3].clone(),
        ];
        assert!(matches!(
            materialized_links(root.path(), &overflowing, None, Limits::default()),
            Err(Error::Limit)
        ));
    }
    #[test]
    fn windows_casefolded_link_chains_preserve_materialized_hardlink_targets() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("file"), b"file").unwrap();
        let entries = vec![
            Entry {
                path: "a".into(),
                kind: Kind::Symlink("B".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "b".into(),
                kind: Kind::Symlink("FILE".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "h".into(),
                kind: Kind::Hardlink("A".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "file".into(),
                kind: Kind::File,
                size: 4,
                executable: false,
            },
        ];
        materialized_links(root.path(), &entries, None, Limits::default()).unwrap();
        std::fs::write(root.path().join("h"), b"changed").unwrap();
        assert_eq!(std::fs::read(root.path().join("a")).unwrap(), b"changed");
        assert_eq!(std::fs::read(root.path().join("file")).unwrap(), b"file");
        assert_eq!(std::fs::read(root.path().join("b")).unwrap(), b"file");
    }
    #[test]
    #[cfg(unix)]
    fn unix_hardlink_chains_resolve_once_and_reject_cycles() {
        use std::os::unix::fs::MetadataExt;
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("file"), b"runtime").unwrap();
        let entries: Vec<_> = (0..4096)
            .map(|i| Entry {
                path: format!("h{i:04}").into(),
                kind: Kind::Hardlink(if i == 4095 {
                    "file".into()
                } else {
                    format!("h{:04}", i + 1)
                }),
                size: 0,
                executable: false,
            })
            .collect();
        links(root.path(), &entries, None, Limits::default()).unwrap();
        let inode = std::fs::metadata(root.path().join("file")).unwrap().ino();
        for entry in &entries {
            assert_eq!(
                std::fs::metadata(root.path().join(&entry.path))
                    .unwrap()
                    .ino(),
                inode
            );
        }
        let root = tempfile::tempdir().unwrap();
        let cyclic = vec![
            Entry {
                path: "a".into(),
                kind: Kind::Hardlink("b".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "b".into(),
                kind: Kind::Hardlink("a".into()),
                size: 0,
                executable: false,
            },
        ];
        assert!(links(root.path(), &cyclic, None, Limits::default()).is_err());
        assert!(!root.path().join("a").exists());
    }
    #[test]
    #[cfg(unix)]
    fn dangling_links_are_preserved_but_directory_alias_escapes_are_rejected() {
        let root = tempfile::tempdir().unwrap();
        let dangling = vec![Entry {
            path: "optional".into(),
            kind: Kind::Symlink("missing/runtime".into()),
            size: 0,
            executable: false,
        }];
        validate(&dangling, Limits::default(), None).unwrap();
        links(root.path(), &dangling, None, Limits::default()).unwrap();
        assert_eq!(
            std::fs::read_link(root.path().join("optional")).unwrap(),
            PathBuf::from("missing/runtime")
        );
        let escaped = vec![
            Entry {
                path: "deep/path/alias".into(),
                kind: Kind::Symlink("../../top".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "deep/path/escape".into(),
                kind: Kind::Symlink("alias/../../outside".into()),
                size: 0,
                executable: false,
            },
        ];
        std::fs::create_dir(root.path().join("top")).unwrap();
        validate(&escaped, Limits::default(), None).unwrap();
        assert!(matches!(
            links(root.path(), &escaped, None, Limits::default()),
            Err(Error::Unsafe(_))
        ));
        let cyclic = vec![
            Entry {
                path: "a".into(),
                kind: Kind::Symlink("b".into()),
                size: 0,
                executable: false,
            },
            Entry {
                path: "b".into(),
                kind: Kind::Symlink("a".into()),
                size: 0,
                executable: false,
            },
        ];
        assert!(matches!(
            links(root.path(), &cyclic, None, Limits::default()),
            Err(Error::Unsafe(_))
        ));
    }
    #[test]
    fn non_utf8_validation_returns_an_error() {
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStringExt;
            let entries = vec![Entry {
                path: std::ffi::OsString::from_vec(vec![0xff]).into(),
                kind: Kind::File,
                size: 0,
                executable: false,
            }];
            assert!(matches!(
                validate(&entries, Limits::default(), None),
                Err(Error::Unsafe(_))
            ));
        }
    }
    #[test]
    fn xz_streams_are_bounded_and_do_not_buffer_the_payload() {
        let parent = tempfile::tempdir().unwrap();
        let input = parent.path().join("tool.xz");
        let mut compressed = std::fs::File::create(&input).unwrap();
        lzma_rs::xz_compress(&mut std::io::Cursor::new(b"tool"), &mut compressed).unwrap();
        let extracted = extract(
            &input,
            &artifact("tool.xz", "xz", vec![crate::Bin::new("tool")]),
            parent.path(),
            Limits::default(),
        )
        .unwrap();
        assert_eq!(
            std::fs::read(extracted.tree.path().join("tool")).unwrap(),
            b"tool"
        );
        assert!(
            extract(
                &input,
                &artifact("tool.xz", "xz", vec![crate::Bin::new("tool")]),
                parent.path(),
                Limits {
                    bytes: 2,
                    entries: 100
                }
            )
            .is_err()
        );
    }
}