jubarte-cli 0.19.0

The jubarte engine's command line: every operation of the library behind one clap surface, plus self-update
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! `jubarte self-update`: replace this binary with a GitHub release when the
//! user runs `jubarte self-update` (docs/SELF_UPDATE.md).
//!
//! The release lookup, SHA-256 check against `SHA256SUMS.txt`, archive
//! extraction and binary swap are the
//! [`self_update`](https://docs.rs/self_update) crate's; the zipsign
//! signature check is [`verify_signature`](crate::update::verify_signature)
//! (`zipsign.rs`), which `self_update`
//! runs on the downloaded archive before extracting it. This module builds
//! the call the binary makes: it picks the release archive for this platform
//! (`asset_target`), decides whether the target is newer
//! (`plan`) and refuses to ask on a non-interactive stdin
//! (`preflight`). The signature rule lives in `signature_required`,
//! split out so it is unit-tested without I/O.
//!
//! Entry points: `run` for the command itself, `plan` / `step` /
//! `preflight` / `signature_required` for the decisions.

use std::io::{BufRead, IsTerminal, Write};

use self_update::backends::github;
use self_update::version::cmp_versions;

mod zipsign;
pub use zipsign::{ReleaseKey, verify_signature};

const REPO_OWNER: &str = "jandira-tech";
const REPO_NAME: &str = "jubarte";
const SUMS_ASSET: &str = "SHA256SUMS.txt";

/// The ed25519 public keys trusted to sign release archives (zipsign), any
/// one of which must have signed a release from [`FIRST_SIGNED_RELEASE`] on.
///
/// Empty until the owner commits a key, and with no key the updater checks
/// `SHA256SUMS.txt` alone, as before. To trust a key, commit the 32-byte file
/// `zipsign gen-key` writes and list it here:
///
/// ```text
/// const RELEASE_KEYS: &[ReleaseKey] =
///     &[*include_bytes!("../../../keys/release-signing.pub")];
/// ```
///
/// A file that is not exactly 32 bytes fails the build. Set
/// [`FIRST_SIGNED_RELEASE`] in the same commit; docs/SELF_UPDATE.md has the
/// steps, including key rotation.
const RELEASE_KEYS: &[ReleaseKey] = &[];

/// The first release whose archives `release.yml` signed, without a leading
/// `v` (`Some("0.11.0")`). `None` until [`RELEASE_KEYS`] holds a key.
const FIRST_SIGNED_RELEASE: Option<&str> = None;

/// Bytes `jubarte self-update` will download, or inflate from the one
/// expected member of a release zip, before it refuses and leaves the
/// installed binary in place.
///
/// Published archives are about 18 MiB (`v0.17.0`). This is several times
/// that size. The tar.gz member's own inflation cap is a separate check.
const UPDATE_ARCHIVE_BYTE_BUDGET: u64 = 128 * 1024 * 1024;

/// The flags `jubarte self-update` accepts, resolved from the CLI before
/// [`run`] sees them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Options {
    /// Print the installed and the latest version and install nothing
    /// (`--check`).
    pub check: bool,
    /// Install without the interactive prompt (`--yes`).
    pub yes: bool,
    /// Install this release (`0.10.0` or `v0.10.0`; `--version`). A
    /// request may downgrade; the installed version itself is up to date
    /// and is not installed again.
    pub version: Option<String>,
}

/// The decision [`plan`] returns, once the target release is known.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Plan {
    /// The installed version is the target (or already newer, when no
    /// `--version` was asked for): nothing to do.
    UpToDate {
        /// The installed version.
        current: String,
    },
    /// Replace the installed version with `to`.
    Install {
        /// The installed version.
        from: String,
        /// The release to install.
        to: String,
    },
}

/// The release archive suffix this binary will look up (`macos-aarch64`,
/// `linux-x86_64`, `linux-musl-x86_64`, …), matching the names
/// `release.yml` publishes. `None`
/// for an OS / arch pair no archive is built for.
#[must_use]
pub fn asset_target() -> Option<&'static str> {
    asset_target_for(
        std::env::consts::OS,
        std::env::consts::ARCH,
        cfg!(target_env = "musl"),
    )
}

/// `musl` picks the static archive: a musl build must not replace itself
/// with the glibc one, which needs a loader Alpine lacks. No archive name
/// holds another, because `self_update` matches assets by substring.
fn asset_target_for(os: &str, arch: &str, musl: bool) -> Option<&'static str> {
    Some(match (os, arch, musl) {
        ("macos", "aarch64", false) => "macos-aarch64",
        ("macos", "x86_64", false) => "macos-x86_64",
        ("linux", "aarch64", false) => "linux-aarch64",
        ("linux", "x86_64", false) => "linux-x86_64",
        ("linux", "aarch64", true) => "linux-musl-aarch64",
        ("linux", "x86_64", true) => "linux-musl-x86_64",
        ("windows", "x86_64", false) => "windows-x86_64",
        _ => return None,
    })
}

/// Path of the binary inside the release archive, as `self_update` expects
/// it (`{{ version }}` is filled in by the crate).
fn bin_path_in_archive(target: &str) -> String {
    format!(
        "jubarte-{{{{ version }}}}-{target}/jubarte{}",
        std::env::consts::EXE_SUFFIX
    )
}

/// Refuse to start when the command would have to prompt and the stdin
/// channel is not a terminal. None of the operation is touched, not even a
/// network lookup.
///
/// # Errors
///
/// A message when neither [`Options::check`] nor [`Options::yes`] is set
/// and `interactive` is `false`: passing `--check` or `--yes`, or being on a
/// terminal, lets the run continue.
pub fn preflight(opts: &Options, interactive: bool) -> Result<(), String> {
    if opts.check || opts.yes || interactive {
        Ok(())
    } else {
        Err("no terminal to confirm on; pass --yes to install or --check to only look".into())
    }
}

/// Strip one leading `v` so `v0.10.0` and `0.10.0` name the same release.
fn bare(version: &str) -> &str {
    version.strip_prefix('v').unwrap_or(version)
}

/// Decide between staying and installing for a given installed version and
/// the version `self_update` resolved on GitHub.
///
/// Without a requested version only a strictly newer release installs; a
/// requested version installs whenever it differs from the installed one
/// (downgrades included); the installed version is [`Plan::UpToDate`]. A leading `v` is stripped, so
/// `v0.10.0` and `0.10.0` name the same release.
///
/// # Errors
///
/// A message when either version is not semver.
pub fn plan(current: &str, target: &str, requested: bool) -> Result<Plan, String> {
    let (current, target) = (bare(current), bare(target));
    let order = cmp_versions(target, current).map_err(|e| format!("version {target}: {e}"))?;
    let install = if requested {
        order.is_ne()
    } else {
        order.is_gt()
    };
    Ok(if install {
        Plan::Install {
            from: current.to_string(),
            to: target.to_string(),
        }
    } else {
        Plan::UpToDate {
            current: current.to_string(),
        }
    })
}

/// What `run` does once the release is resolved: report and stop, or ask
/// (unless `--yes`) and install. Pure, so the "`--check` never installs"
/// rule is unit-tested without the network.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Step {
    /// Print `text` and stop. Nothing is downloaded or replaced.
    Report {
        /// The line to print.
        text: String,
    },
    /// Confirm unless `opts.yes`, then replace the running binary.
    Install {
        /// The installed version.
        from: String,
        /// The release to install.
        to: String,
    },
}

/// `decision` is [`plan`]'s answer; `resolved` is the bare release version
/// the lookup returned (the up-to-date message quotes it).
#[must_use]
pub fn step(opts: &Options, decision: &Plan, resolved: &str) -> Step {
    match decision {
        Plan::UpToDate { current } => Step::Report {
            text: format!("jubarte {current} is up to date (latest release {resolved})."),
        },
        Plan::Install { from, to } if opts.check => Step::Report {
            text: format!(
                "jubarte {from} is installed; {to} is available. Run `jubarte self-update` to install it."
            ),
        },
        Plan::Install { from, to } => Step::Install {
            from: from.clone(),
            to: to.clone(),
        },
    }
}

/// `jubarte self-update`. `Ok` means the run finished without error: the
/// binary is replaced only when an install completes, and `--check`, an
/// up-to-date release or a declined prompt leave it as it was. On failure
/// the installed binary is unchanged. Writes progress to
/// stdout, the prompt to stderr, and reads the answer from stdin.
///
/// The flow is: [`preflight`] → resolve the release for this platform
/// ([`asset_target`]) → decide ([`plan`]) → act ([`step`]) → optional prompt
/// → optional signature rule ([`signature_required`]) → `self_update`
/// install. A prompt `y` / `Y` / `yes` confirms; anything else is "no".
///
/// # Errors
///
/// A message for one of:
/// - the platform has no published archive ([`asset_target`] is `None`);
/// - the [`preflight`] check refused the run;
/// - the GitHub release lookup failed or returned no release;
/// - the network or GitHub error inside the `self_update` installer;
/// - the checksum download or verification did not match;
/// - a signature was required but missing or did not verify against
///   [`signature_required`];
/// - the archive is over `UPDATE_ARCHIVE_BYTE_BUDGET`, lists the expected
///   binary more than once, or inflates that binary past the budget;
/// - the binary swap step failed.
pub fn run(opts: &Options) -> Result<(), String> {
    let interactive = std::io::stdin().is_terminal();
    preflight(opts, interactive)?;
    let target = asset_target().ok_or_else(|| {
        format!(
            "no release archive is built for {}-{}; build from source",
            std::env::consts::OS,
            std::env::consts::ARCH
        )
    })?;
    let current = env!("CARGO_PKG_VERSION");

    let mut builder = github::Update::configure();
    builder
        .repo_owner(REPO_OWNER)
        .repo_name(REPO_NAME)
        .bin_name("jubarte")
        .target(target)
        .current_version(current)
        .bin_path_in_archive(bin_path_in_archive(target))
        .verify_binary(extracted_binary_is_regular_file)
        .checksum_from_asset(SUMS_ASSET)
        .show_output(false)
        .show_download_progress(interactive)
        .no_confirm(true);
    let lookup = builder.build().map_err(|e| e.to_string())?;
    let release = match &opts.version {
        Some(v) => lookup
            .get_release_version(&format!("v{}", bare(v)))
            .map(Some),
        None => lookup
            .get_latest_release()
            .map(|releases| releases.into_vec().into_iter().next()),
    }
    .map_err(|e| format!("GitHub release lookup failed: {e}"))?
    .ok_or("GitHub lists no release")?;

    let decision = plan(current, release.version(), opts.version.is_some())?;
    let (from, to) = match step(opts, &decision, bare(release.version())) {
        Step::Report { text } => {
            println!("{text}");
            return Ok(());
        }
        Step::Install { from, to } => (from, to),
    };
    if !opts.yes && !confirm(&from, &to)? {
        println!("Nothing changed.");
        return Ok(());
    }

    let signed = signature_required(&to, FIRST_SIGNED_RELEASE, !RELEASE_KEYS.is_empty())?;
    let member = resolved_bin_path(target, &to);
    // Before extraction: cap the download and the inflated member, and refuse
    // an archive that lists that member twice. The signature decision above
    // is unchanged: this hook runs it only when that decision already said to.
    builder.verify_archive(move |archive| {
        confine_update_zip(archive, &member, UPDATE_ARCHIVE_BYTE_BUDGET)
            .map_err(self_update::Error::archive_verification_rejected)?;
        if signed {
            verify_signature(archive, RELEASE_KEYS)
                .map_err(self_update::Error::archive_verification_rejected)?;
        }
        Ok(())
    });
    if !signed && !RELEASE_KEYS.is_empty() {
        eprintln!("note: {to} predates signed releases; only its SHA-256 is checked.");
    }
    let installer = builder
        .release_tag(format!("v{to}"))
        .build()
        .map_err(|e| e.to_string())?;
    installer
        .update()
        .map_err(|e| format!("update to {to} failed; the installed binary is unchanged: {e}"))?;
    println!("jubarte {from} -> {to} installed.");
    Ok(())
}

/// Whether installing `target_version` must pass a zipsign signature check.
///
/// True only when `keys_present` and the release sorts at or after
/// `first_signed`: releases published before signing began carry no
/// signature, so a `--version` downgrade to one of them is checked by its
/// SHA-256 alone. A `v` prefix on either version is stripped before the
/// comparison.
///
/// # Errors
///
/// A message when `keys_present` and `first_signed` are both set but either
/// side is not semver.
pub fn signature_required(
    target_version: &str,
    first_signed: Option<&str>,
    keys_present: bool,
) -> Result<bool, String> {
    let Some(first) = first_signed.filter(|_| keys_present) else {
        return Ok(false);
    };
    let (target, first) = (bare(target_version), bare(first));
    let order = cmp_versions(target, first)
        .map_err(|e| format!("version {target} against first signed release {first}: {e}"))?;
    Ok(order.is_ge())
}

fn confirm(from: &str, to: &str) -> Result<bool, String> {
    eprint!("Replace jubarte {from} with {to}? [y/N] ");
    std::io::stderr().flush().map_err(|e| e.to_string())?;
    let mut answer = String::new();
    std::io::stdin()
        .lock()
        .read_line(&mut answer)
        .map_err(|e| e.to_string())?;
    Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes" | "YES"))
}

/// The `verify_binary` hook `run` registers (ZIP-16/#639): refuse the
/// extracted binary when it is anything but a regular file. `self_update`
/// already refuses a symlink *zip* entry in its single-file path, but its
/// tar path delegates to `tar`'s `unpack_in`, which restores a symlink
/// entry as a real link whose target is not confined to the staging
/// directory — a crafted release archive could then install any path's
/// contents as the new binary. `symlink_metadata`, not `metadata`, sees
/// the entry itself rather than its target.
fn extracted_binary_is_regular_file(path: &std::path::Path) -> self_update::Result<()> {
    let metadata = std::fs::symlink_metadata(path).map_err(|e| {
        self_update::Error::verification_rejected(format!(
            "the extracted binary {} cannot be inspected: {e}",
            path.display()
        ))
    })?;
    if metadata.is_file() {
        Ok(())
    } else {
        Err(self_update::Error::verification_rejected(format!(
            "the extracted binary {} is not a regular file",
            path.display()
        )))
    }
}

/// Path of the binary inside a release archive once `{{ version }}` is the
/// release being installed. `self_update` fills that token itself; the
/// pre-extract check has to use the same path.
fn resolved_bin_path(target: &str, version: &str) -> String {
    bin_path_in_archive(target).replace("{{ version }}", version)
}

/// Gate the downloaded release archive before `self_update` extracts it.
///
/// `run` registers this as the `verify_archive` hook, which runs after the
/// checksum and before a byte of the archive is unpacked. `member` is the
/// binary path inside the archive (`jubarte-<version>-<target>/jubarte` or
/// `.exe`). A file larger than `budget` is refused. A zip whose expected
/// member appears more than once, or whose expected member inflates past
/// `budget`, is refused. A gzipped tar is refused when its expected member
/// is a symlink or a hardlink, when that member's mode carries setuid,
/// setgid or sticky bits, when any entry climbs out of the extract
/// directory, or when the tar inflates past `budget`. Any other bytes are
/// left alone once the download itself fits.
fn confine_update_zip(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
    let len = std::fs::metadata(archive)
        .map_err(|e| {
            format!(
                "update archive {} cannot be inspected: {e}",
                archive.display()
            )
        })?
        .len();
    if len > budget {
        return Err(format!(
            "update archive is {len} bytes, over the {budget}-byte download budget"
        ));
    }
    let mut file = std::fs::File::open(archive)
        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
    // A zip is told by its end record, not by a leading `PK`: a zipsign
    // signature sits before the zip and zip/self_update still read it
    // (#2084 review). No end record and no `PK`: a gzip is the tar.gz the
    // tar gate reads; anything else is not an archive this gate knows.
    let Some(copies) = zip_member_copies(&mut file, len, member)? else {
        if zip_magic(&mut file)? {
            return Err("update archive has no zip end record".into());
        }
        if gzip_magic(&mut file)? {
            return confine_update_tar(archive, member, budget);
        }
        return Ok(());
    };
    if copies > 1 {
        return Err(format!("update archive lists {member} more than once"));
    }
    if copies == 0 {
        return Err(format!("update archive has no member {member}"));
    }
    inflate_member_within_budget(archive, member, budget)
}

fn zip_magic(file: &mut std::fs::File) -> Result<bool, String> {
    use std::io::{Read, Seek, SeekFrom};
    file.seek(SeekFrom::Start(0))
        .map_err(|e| format!("update archive cannot be rewound: {e}"))?;
    let mut magic = [0u8; 2];
    let read = file
        .read(&mut magic)
        .map_err(|e| format!("update archive cannot be read: {e}"))?;
    Ok(read == 2 && magic == [0x50, 0x4b])
}

/// How many central-directory entries name `member`, or `None` when the
/// file has no zip end record.
///
/// `zip`'s reader keeps one entry per name, so a repeated member is invisible
/// there and the first copy would be the one installed. The count comes from
/// the central directory itself. Each name is the one `zip` resolves (an
/// adopted 0x7075 Unicode Path included), and a directory that a leading
/// prefix moved past its recorded offset is found where `zip` finds it.
fn zip_member_copies(
    file: &mut std::fs::File,
    len: u64,
    member: &str,
) -> Result<Option<u32>, String> {
    const EOCD_LEN: u64 = 22;
    const MAX_COMMENT: u64 = 65_535;
    if len < EOCD_LEN {
        return Ok(None);
    }
    let tail_len = len.min(EOCD_LEN.saturating_add(MAX_COMMENT));
    let tail_at = len.saturating_sub(tail_len);
    let tail_bytes = usize::try_from(tail_len)
        .map_err(|_| "update archive is too large to inspect".to_string())?;
    let mut tail = vec![0u8; tail_bytes];
    read_exact_at(file, tail_at, &mut tail)?;
    let Some(eocd) = find_eocd(&tail) else {
        return Ok(None);
    };
    let entries = le_u16(&tail, eocd.saturating_add(10))?;
    let cd_size = u64::from(le_u32(&tail, eocd.saturating_add(12))?);
    let cd_offset = u64::from(le_u32(&tail, eocd.saturating_add(16))?);
    if entries == u16::MAX || cd_size == u64::from(u32::MAX) || cd_offset == u64::from(u32::MAX) {
        return Err("update archive uses ZIP64, which this check refuses".into());
    }
    // Bytes before the zip (a zipsign signature) shift the directory by
    // the gap between where it ends and where the end record sits; zip
    // reads it at the recorded offset first, then shifted.
    let eocd_at = tail_at.saturating_add(eocd as u64);
    let recorded_end = cd_offset
        .checked_add(cd_size)
        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
    let shift = eocd_at
        .checked_sub(recorded_end)
        .ok_or_else(|| "update archive central directory runs past its end record".to_string())?;
    let mut signature = [0u8; 4];
    let at_recorded = cd_size == 0
        || (read_exact_at(file, cd_offset, &mut signature).is_ok()
            && signature == [0x50, 0x4b, 0x01, 0x02]);
    let base = if at_recorded { 0 } else { shift };
    let cd_start = cd_offset
        .checked_add(base)
        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
    let cd_end = recorded_end
        .checked_add(base)
        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
    if cd_end > len {
        return Err("update archive central directory runs past the file".into());
    }
    let mut at = cd_start;
    let mut copies = 0u32;
    let mut seen = 0u16;
    let mut name_and_extra = Vec::new();
    while at < cd_end {
        let mut header = [0u8; 46];
        read_exact_at(file, at, &mut header)?;
        if header.get(..4) != Some(&[0x50, 0x4b, 0x01, 0x02]) {
            return Err("update archive central directory is truncated".into());
        }
        let name_len = u64::from(le_u16(&header, 28)?);
        let extra_len = u64::from(le_u16(&header, 30)?);
        let comment_len = u64::from(le_u16(&header, 32)?);
        let step = 46u64
            .checked_add(name_len)
            .and_then(|n| n.checked_add(extra_len))
            .and_then(|n| n.checked_add(comment_len))
            .ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
        let next = at
            .checked_add(step)
            .ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
        if next > cd_end {
            return Err("update archive central directory entry runs past the directory".into());
        }
        let name_at = at
            .checked_add(46)
            .ok_or_else(|| "update archive member name is out of range".to_string())?;
        let name_bytes = usize::try_from(name_len)
            .map_err(|_| "update archive member name is too long".to_string())?;
        let extra_bytes = usize::try_from(extra_len)
            .map_err(|_| "update archive extra field is too long".to_string())?;
        // One buffer for every entry: name then extra field, each at most
        // 64 KiB, as the header records them.
        name_and_extra.resize(name_bytes.saturating_add(extra_bytes), 0);
        if !name_and_extra.is_empty() {
            read_exact_at(file, name_at, &mut name_and_extra)?;
        }
        let (raw_name, extra) = name_and_extra.split_at(name_bytes);
        let flags = le_u16(&header, 8)?;
        let name = crate::admission::zip_entry_name_raw(raw_name, flags, extra)
            .map_err(|e| format!("update archive member name cannot be read: {e}"))?;
        if member_names_match(name.as_bytes(), member) {
            copies = copies.saturating_add(1);
        }
        seen = seen
            .checked_add(1)
            .ok_or_else(|| "update archive has too many entries".to_string())?;
        at = next;
    }
    if seen != entries {
        return Err("update archive central directory does not match its end record".into());
    }
    Ok(Some(copies))
}

fn find_eocd(tail: &[u8]) -> Option<usize> {
    let last = tail.len().checked_sub(22)?;
    let mut at = last;
    loop {
        if tail.get(at..at.checked_add(4)?) == Some(&[0x50, 0x4b, 0x05, 0x06][..]) {
            let comment = usize::from(le_u16(tail, at.saturating_add(20)).ok()?);
            let end = at.checked_add(22)?.checked_add(comment)?;
            if end == tail.len() {
                return Some(at);
            }
        }
        if at == 0 {
            return None;
        }
        at = at.saturating_sub(1);
    }
}

fn le_u16(bytes: &[u8], at: usize) -> Result<u16, String> {
    let mut buf = [0u8; 2];
    buf.copy_from_slice(
        bytes
            .get(
                at..at
                    .checked_add(2)
                    .ok_or_else(|| "update archive field is out of range".to_string())?,
            )
            .ok_or_else(|| "update archive field is out of range".to_string())?,
    );
    Ok(u16::from_le_bytes(buf))
}

fn le_u32(bytes: &[u8], at: usize) -> Result<u32, String> {
    let mut buf = [0u8; 4];
    buf.copy_from_slice(
        bytes
            .get(
                at..at
                    .checked_add(4)
                    .ok_or_else(|| "update archive field is out of range".to_string())?,
            )
            .ok_or_else(|| "update archive field is out of range".to_string())?,
    );
    Ok(u32::from_le_bytes(buf))
}

fn member_names_match(entry: &[u8], member: &str) -> bool {
    let entry = entry.strip_prefix(b"./").unwrap_or(entry);
    if entry.ends_with(b"/") {
        return false;
    }
    let member = member.strip_prefix("./").unwrap_or(member).as_bytes();
    entry.len() == member.len()
        && entry
            .iter()
            .zip(member)
            .all(|(got, want)| *got == *want || (*got == b'\\' && *want == b'/'))
}

fn read_exact_at(file: &mut std::fs::File, at: u64, buf: &mut [u8]) -> Result<(), String> {
    use std::io::{Read, Seek, SeekFrom};
    file.seek(SeekFrom::Start(at))
        .map_err(|e| format!("update archive seek failed: {e}"))?;
    file.read_exact(buf)
        .map_err(|e| format!("update archive read failed: {e}"))
}

/// Count the bytes the expected member actually inflates to, and stop one
/// byte past `budget`. The declared uncompressed size is not the limit:
/// `self_update` copies the stream with no cap of its own.
fn inflate_member_within_budget(
    archive: &std::path::Path,
    member: &str,
    budget: u64,
) -> Result<(), String> {
    use std::io::{Read, copy, sink};
    let file = std::fs::File::open(archive)
        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
    let mut zip = zip::ZipArchive::new(file)
        .map_err(|e| format!("update archive is not a readable zip: {e}"))?;
    let mut matched = None;
    for index in 0..zip.len() {
        let entry = zip
            .by_index(index)
            .map_err(|e| format!("update archive entry {index} cannot be read: {e}"))?;
        let name = entry
            .name()
            .map_err(|e| format!("update archive entry {index} has no name: {e}"))?;
        if member_names_match(name.as_bytes(), member) {
            matched = Some(index);
            break;
        }
    }
    let Some(index) = matched else {
        return Err(format!("update archive has no member {member}"));
    };
    let mut entry = zip
        .by_index(index)
        .map_err(|e| format!("update member {member} cannot be read: {e}"))?;
    let inflated = copy(
        &mut (&mut entry).take(budget.saturating_add(1)),
        &mut sink(),
    )
    .map_err(|e| format!("update member {member} could not be inflated: {e}"))?;
    if inflated > budget {
        Err(format!(
            "update member {member} inflates past the {budget}-byte budget"
        ))
    } else {
        Ok(())
    }
}

fn gzip_magic(file: &mut std::fs::File) -> Result<bool, String> {
    use std::io::{Read, Seek, SeekFrom};
    file.seek(SeekFrom::Start(0))
        .map_err(|e| format!("update archive cannot be rewound: {e}"))?;
    let mut magic = [0u8; 2];
    let read = file
        .read(&mut magic)
        .map_err(|e| format!("update archive cannot be read: {e}"))?;
    Ok(read == 2 && magic == [0x1f, 0x8b])
}

/// Walk a gzipped tar the way a Unix release archive is packed. `self_update`
/// then asks `tar` to unpack the one member, which restores a symlink or a
/// hardlink as a real link and keeps setuid bits. Refuse those before that
/// unpack. The decompressed byte count stops at `budget`.
fn confine_update_tar(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
    let file = std::fs::File::open(archive)
        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
    let mut decoder = flate2::read::GzDecoder::new(file);
    let mut inflated = 0u64;
    let mut zero_blocks = 0u8;
    let mut copies = 0u32;
    // The tar crate's extension entries: a GNU `L` long name, a GNU `K`
    // long link and a PAX `x` record set each describe the next member.
    let mut long_name: Option<Vec<u8>> = None;
    let mut long_link = false;
    let mut pax: Option<Vec<u8>> = None;
    loop {
        let mut header = [0u8; 512];
        if !read_tar_block(&mut decoder, &mut header, &mut inflated, budget)? {
            break;
        }
        if header.iter().all(|byte| *byte == 0) {
            zero_blocks = zero_blocks.saturating_add(1);
            if zero_blocks == 2 {
                break;
            }
            continue;
        }
        zero_blocks = 0;
        if !tar_checksum_ok(&header) {
            return Err("update archive is not a tar".into());
        }
        let typeflag = *header.get(156).unwrap_or(&0);
        let extension = matches!(typeflag, b'L' | b'K' | b'x' | b'g');
        let mut size = tar_octal(header.get(124..136).unwrap_or(&[]))?;
        if !extension
            && let Some(records) = pax.as_deref()
            && let Some(pax_size) = pax_value(records, b"size")?
        {
            size = std::str::from_utf8(pax_size)
                .ok()
                .and_then(|text| text.parse::<u64>().ok())
                .ok_or_else(|| "update archive PAX size is not a number".to_string())?;
        }
        if tar_magic_recognized(&header) && matches!(typeflag, b'L' | b'K' | b'x') {
            let twice = match typeflag {
                b'L' => long_name.is_some(),
                b'K' => long_link,
                _ => pax.is_some(),
            };
            if twice {
                return Err("update archive describes one member twice".into());
            }
            let body = read_tar_extension(&mut decoder, size, &mut inflated, budget)?;
            match typeflag {
                b'L' => long_name = Some(body),
                b'K' => long_link = true,
                _ => pax = Some(body),
            }
            continue;
        }
        let name_bytes = match long_name.take() {
            Some(mut bytes) => {
                if bytes.last() == Some(&0) {
                    bytes.pop();
                }
                bytes
            }
            None => match pax.as_deref().map(|records| pax_value(records, b"path")) {
                Some(Ok(Some(path))) => path.to_vec(),
                Some(Err(e)) => return Err(e),
                _ => tar_entry_name(&header)?.into_bytes(),
            },
        };
        pax = None;
        long_link = false;
        let name = String::from_utf8(name_bytes)
            .map_err(|_| "update archive tar name is not UTF-8".to_string())?;
        if tar_name_escapes(&name) {
            return Err(format!(
                "update archive entry {name} escapes the extraction directory"
            ));
        }
        let mode = tar_octal(header.get(100..108).unwrap_or(&[]))?;
        if member_names_match(name.as_bytes(), member) {
            match typeflag {
                b'2' => return Err(format!("update member {member} is a symlink")),
                b'1' => return Err(format!("update member {member} is a hardlink")),
                b'0' | 0 => {}
                _ => {
                    return Err(format!("update member {member} is not a regular file"));
                }
            }
            if mode & 0o7000 != 0 {
                return Err(format!(
                    "update member {member} mode {mode:o} carries setuid, setgid, or sticky bits"
                ));
            }
            copies = copies.saturating_add(1);
        }
        skip_tar_body(&mut decoder, size, &mut inflated, budget)?;
    }
    if long_name.is_some() || long_link || pax.is_some() {
        return Err("update archive describes a member that never follows".into());
    }
    if copies > 1 {
        return Err(format!("update archive lists {member} more than once"));
    }
    if copies == 0 {
        return Err(format!("update archive has no member {member}"));
    }
    Ok(())
}

/// The tar crate honours `L`, `K` and `x` entries only under a ustar
/// (`"ustar\0"`, `"00"`) or GNU (`"ustar "`, `" \0"`) magic.
fn tar_magic_recognized(header: &[u8; 512]) -> bool {
    let magic = header.get(257..263).unwrap_or(&[]);
    let version = header.get(263..265).unwrap_or(&[]);
    (magic == b"ustar\0" && version == b"00") || (magic == b"ustar " && version == b" \0")
}

/// Largest GNU long name or PAX record set the gate reads into memory.
const TAR_EXTENSION_LIMIT: u64 = 1 << 20;

fn read_tar_extension(
    reader: &mut impl std::io::Read,
    size: u64,
    inflated: &mut u64,
    budget: u64,
) -> Result<Vec<u8>, String> {
    if size > TAR_EXTENSION_LIMIT {
        return Err(format!(
            "update archive extension header of {size} bytes exceeds {TAR_EXTENSION_LIMIT}"
        ));
    }
    let len = usize::try_from(size)
        .map_err(|_| "update archive extension header is too large".to_string())?;
    let mut body = vec![0u8; len];
    read_exact_capped(reader, &mut body, inflated, budget)?;
    let pad = (512 - size % 512) % 512;
    let mut padding = [0u8; 512];
    let pad_len = usize::try_from(pad).unwrap_or(0);
    read_exact_capped(
        reader,
        padding
            .get_mut(..pad_len)
            .ok_or_else(|| "update archive tar padding is out of range".to_string())?,
        inflated,
        budget,
    )?;
    Ok(body)
}

/// The first value for `key` among PAX records `"<len> <key>=<value>\n"`.
/// A malformed record set is a refusal: the extractor and the gate must
/// not read it two ways.
fn pax_value<'a>(records: &'a [u8], key: &[u8]) -> Result<Option<&'a [u8]>, String> {
    let malformed = || "update archive PAX header is malformed".to_string();
    let mut rest = records;
    while !rest.is_empty() {
        let space = rest
            .iter()
            .position(|byte| *byte == b' ')
            .ok_or_else(malformed)?;
        let len = std::str::from_utf8(rest.get(..space).ok_or_else(malformed)?)
            .ok()
            .and_then(|text| text.parse::<usize>().ok())
            .ok_or_else(malformed)?;
        let record = rest.get(..len).ok_or_else(malformed)?;
        let body = record
            .get(space.saturating_add(1)..)
            .and_then(|body| body.strip_suffix(b"\n"))
            .ok_or_else(malformed)?;
        let equals = body
            .iter()
            .position(|byte| *byte == b'=')
            .ok_or_else(malformed)?;
        if body.get(..equals) == Some(key) {
            return Ok(body.get(equals.saturating_add(1)..));
        }
        rest = rest.get(len..).ok_or_else(malformed)?;
    }
    Ok(None)
}

/// `Ok(false)` is a clean end of the gzip member. A short read in the middle
/// of a header is a refusal.
fn read_tar_block(
    reader: &mut impl std::io::Read,
    header: &mut [u8; 512],
    inflated: &mut u64,
    budget: u64,
) -> Result<bool, String> {
    let mut filled = 0usize;
    while filled < header.len() {
        if *inflated >= budget {
            return Err(format!(
                "update archive inflates past the {budget}-byte budget"
            ));
        }
        let room = budget.saturating_sub(*inflated);
        let want = u64::try_from(header.len().saturating_sub(filled)).unwrap_or(u64::MAX);
        let take = usize::try_from(room.min(want)).unwrap_or(0);
        if take == 0 {
            return Err(format!(
                "update archive inflates past the {budget}-byte budget"
            ));
        }
        let end = filled.saturating_add(take);
        let read = reader
            .read(
                header
                    .get_mut(filled..end)
                    .ok_or_else(|| "update archive tar header is out of range".to_string())?,
            )
            .map_err(|e| format!("update archive could not be inflated: {e}"))?;
        if read == 0 {
            if filled == 0 {
                return Ok(false);
            }
            return Err("update archive ended inside a tar header".into());
        }
        filled = filled.saturating_add(read);
        *inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
    }
    Ok(true)
}

fn skip_tar_body(
    reader: &mut impl std::io::Read,
    size: u64,
    inflated: &mut u64,
    budget: u64,
) -> Result<(), String> {
    let padded = size
        .checked_add(511)
        .ok_or_else(|| "update archive tar member is too large".to_string())?
        / 512
        * 512;
    let mut left = padded;
    let mut buf = [0u8; 8192];
    while left > 0 {
        let take = usize::try_from(left.min(8192)).unwrap_or(8192);
        let dest = buf
            .get_mut(..take)
            .ok_or_else(|| "update archive tar member is out of range".to_string())?;
        read_exact_capped(reader, dest, inflated, budget)?;
        left = left.saturating_sub(u64::try_from(take).unwrap_or(left));
    }
    Ok(())
}

fn read_exact_capped(
    reader: &mut impl std::io::Read,
    buf: &mut [u8],
    inflated: &mut u64,
    budget: u64,
) -> Result<(), String> {
    let mut filled = 0usize;
    while filled < buf.len() {
        if *inflated >= budget {
            return Err(format!(
                "update archive inflates past the {budget}-byte budget"
            ));
        }
        let room = budget.saturating_sub(*inflated);
        let want = u64::try_from(buf.len().saturating_sub(filled)).unwrap_or(u64::MAX);
        let take = usize::try_from(room.min(want)).unwrap_or(0);
        if take == 0 {
            return Err(format!(
                "update archive inflates past the {budget}-byte budget"
            ));
        }
        let end = filled.saturating_add(take);
        let read = reader
            .read(
                buf.get_mut(filled..end)
                    .ok_or_else(|| "update archive tar body is out of range".to_string())?,
            )
            .map_err(|e| format!("update archive could not be inflated: {e}"))?;
        if read == 0 {
            return Err("update archive ended inside a tar member".into());
        }
        filled = filled.saturating_add(read);
        *inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
    }
    Ok(())
}

fn tar_checksum_ok(header: &[u8; 512]) -> bool {
    let mut sum = 0u32;
    for (index, byte) in header.iter().enumerate() {
        if (148..156).contains(&index) {
            sum += u32::from(b' ');
        } else {
            sum += u32::from(*byte);
        }
    }
    tar_octal(header.get(148..156).unwrap_or(&[])).ok() == Some(u64::from(sum))
}

fn tar_entry_name(header: &[u8; 512]) -> Result<String, String> {
    let name = tar_c_string(header.get(..100).unwrap_or(&[]))?;
    // Only a ustar header carries a prefix field; a GNU header keeps
    // other data at those bytes, and the tar crate ignores them there.
    let ustar = header.get(257..263) == Some(b"ustar\0") && header.get(263..265) == Some(b"00");
    if !ustar {
        return Ok(name);
    }
    let prefix = tar_c_string(header.get(345..500).unwrap_or(&[]))?;
    if prefix.is_empty() {
        Ok(name)
    } else {
        Ok(format!("{prefix}/{name}"))
    }
}

fn tar_c_string(bytes: &[u8]) -> Result<String, String> {
    let end = bytes
        .iter()
        .position(|byte| *byte == 0)
        .unwrap_or(bytes.len());
    let text = bytes.get(..end).unwrap_or(&[]);
    String::from_utf8(text.to_vec()).map_err(|_| "update archive tar name is not UTF-8".to_string())
}

/// Parsed as the tar crate does: cut at the first NUL, trim blanks on both
/// sides, then read octal digits (an optional leading `+`, as
/// `u64::from_str_radix` allows). An empty field is refused there too.
fn tar_octal(bytes: &[u8]) -> Result<u64, String> {
    let end = bytes
        .iter()
        .position(|byte| *byte == 0)
        .unwrap_or(bytes.len());
    let text = bytes.get(..end).unwrap_or(&[]).trim_ascii();
    let text = text.strip_prefix(b"+").unwrap_or(text);
    if text.is_empty() {
        return Err("update archive tar field is not octal".into());
    }
    let mut value = 0u64;
    for byte in text {
        let digit = byte
            .checked_sub(b'0')
            .filter(|digit| *digit < 8)
            .ok_or_else(|| "update archive tar field is not octal".to_string())?;
        value = value
            .checked_mul(8)
            .and_then(|next| next.checked_add(u64::from(digit)))
            .ok_or_else(|| "update archive tar field is out of range".to_string())?;
    }
    Ok(value)
}

fn tar_name_escapes(name: &str) -> bool {
    use std::path::{Component, Path};
    if name.starts_with('/') || name.starts_with('\\') {
        return true;
    }
    if name.split(['/', '\\']).any(|part| part == "..") {
        return true;
    }
    Path::new(name).components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    })
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn asset_targets_match_the_release_workflow_archives() {
        let glibc = |os, arch| asset_target_for(os, arch, false);
        assert_eq!(glibc("macos", "aarch64"), Some("macos-aarch64"));
        assert_eq!(glibc("macos", "x86_64"), Some("macos-x86_64"));
        assert_eq!(glibc("linux", "aarch64"), Some("linux-aarch64"));
        assert_eq!(glibc("linux", "x86_64"), Some("linux-x86_64"));
        assert_eq!(glibc("windows", "x86_64"), Some("windows-x86_64"));
        // No archive is published for these: refuse rather than pick a wrong one.
        assert_eq!(glibc("windows", "aarch64"), None);
        assert_eq!(glibc("freebsd", "x86_64"), None);
        assert!(asset_target().is_some(), "every CI host has an archive");
    }

    /// #2112: a static musl build updates to the musl archive. The glibc
    /// archive needs a loader Alpine does not have.
    #[test]
    fn a_musl_build_looks_up_the_musl_archive() {
        assert_eq!(
            asset_target_for("linux", "x86_64", true),
            Some("linux-musl-x86_64")
        );
        assert_eq!(
            asset_target_for("linux", "aarch64", true),
            Some("linux-musl-aarch64")
        );
        assert_eq!(asset_target_for("macos", "aarch64", true), None);
    }

    /// Every archive `release.yml` publishes (its `binaries` matrix).
    const PUBLISHED_ARCHIVES: [&str; 7] = [
        "linux-x86_64",
        "linux-aarch64",
        "linux-musl-x86_64",
        "linux-musl-aarch64",
        "macos-x86_64",
        "macos-aarch64",
        "windows-x86_64",
    ];

    /// `self_update` takes the first asset whose name *contains* the
    /// target, so no archive name may hold another: each lookup, through
    /// the crate's own matcher, lands on its own archive whatever the order.
    #[test]
    fn each_target_selects_its_own_archive_among_the_published_ones() {
        for order in [
            PUBLISHED_ARCHIVES.to_vec(),
            PUBLISHED_ARCHIVES.iter().rev().copied().collect(),
        ] {
            let release = self_update::update::Release::builder()
                .version("9.9.9")
                .assets(order.iter().map(|name| {
                    self_update::update::ReleaseAsset::new(
                        format!("jubarte-9.9.9-{name}.zip"),
                        format!("https://example.invalid/{name}"),
                    )
                }))
                .build()
                .expect("release");
            for name in PUBLISHED_ARCHIVES {
                let asset = release.asset_for(name, None).expect(name);
                assert_eq!(asset.name(), format!("jubarte-9.9.9-{name}.zip"));
            }
        }
    }

    /// The overlap the test above guards against: a `-musl` suffix makes
    /// the glibc lookup match the musl archive when it is listed first.
    #[test]
    fn a_suffixed_musl_name_would_steal_the_glibc_lookup() {
        let release = self_update::update::Release::builder()
            .version("9.9.9")
            .assets(["linux-x86_64-musl", "linux-x86_64"].map(|name| {
                self_update::update::ReleaseAsset::new(
                    format!("jubarte-9.9.9-{name}.zip"),
                    format!("https://example.invalid/{name}"),
                )
            }))
            .build()
            .expect("release");
        let asset = release.asset_for("linux-x86_64", None).expect("asset");
        assert_eq!(asset.name(), "jubarte-9.9.9-linux-x86_64-musl.zip");
    }

    #[test]
    fn archive_binary_path_names_the_staged_folder() {
        let path = bin_path_in_archive("macos-aarch64");
        assert_eq!(
            path,
            format!(
                "jubarte-{{{{ version }}}}-macos-aarch64/jubarte{}",
                std::env::consts::EXE_SUFFIX
            )
        );
        assert!(path.contains("{{ version }}"));
    }

    #[test]
    fn without_a_terminal_only_check_or_yes_proceed() {
        let ask = Options::default();
        assert!(preflight(&ask, false).is_err());
        assert!(preflight(&ask, true).is_ok());
        let check = Options {
            check: true,
            ..Options::default()
        };
        assert!(preflight(&check, false).is_ok());
        let yes = Options {
            yes: true,
            ..Options::default()
        };
        assert!(preflight(&yes, false).is_ok());
        // Naming a version still needs an answer.
        let pinned = Options {
            version: Some("0.9.3".into()),
            ..Options::default()
        };
        assert!(preflight(&pinned, false).is_err());
    }

    #[test]
    fn check_reports_and_never_installs() {
        let install = Plan::Install {
            from: "0.10.0".into(),
            to: "0.11.0".into(),
        };
        // --check turns an install decision into a report: Step::Install is
        // unreachable with check set, so nothing is ever downloaded or replaced.
        let look = Options {
            check: true,
            ..Options::default()
        };
        assert_eq!(
            step(&look, &install, "0.11.0"),
            Step::Report {
                text: "jubarte 0.10.0 is installed; 0.11.0 is available. Run `jubarte self-update` to install it.".into()
            }
        );
        // --check wins over --yes too: an explicit look never installs.
        let look_yes = Options {
            check: true,
            yes: true,
            ..Options::default()
        };
        assert!(matches!(
            step(&look_yes, &install, "0.11.0"),
            Step::Report { .. }
        ));
        // Without --check the same decision installs.
        assert_eq!(
            step(&Options::default(), &install, "0.11.0"),
            Step::Install {
                from: "0.10.0".into(),
                to: "0.11.0".into()
            }
        );
        // An up-to-date binary reports and stops whatever the flags say.
        let up_to_date = Plan::UpToDate {
            current: "0.11.0".into(),
        };
        for opts in [
            look,
            look_yes,
            Options {
                yes: true,
                ..Options::default()
            },
            Options::default(),
        ] {
            assert!(matches!(
                step(&opts, &up_to_date, "0.11.0"),
                Step::Report { .. }
            ));
        }
    }

    #[test]
    fn latest_installs_only_when_newer() {
        assert_eq!(
            plan("0.9.3", "v0.10.0", false),
            Ok(Plan::Install {
                from: "0.9.3".into(),
                to: "0.10.0".into()
            })
        );
        assert_eq!(
            plan("0.10.0", "0.10.0", false),
            Ok(Plan::UpToDate {
                current: "0.10.0".into()
            })
        );
        // A newer local build never downgrades to the latest release.
        assert_eq!(
            plan("0.11.0", "0.10.0", false),
            Ok(Plan::UpToDate {
                current: "0.11.0".into()
            })
        );
    }

    #[test]
    fn a_requested_version_installs_even_when_older() {
        assert_eq!(
            plan("0.10.0", "0.9.3", true),
            Ok(Plan::Install {
                from: "0.10.0".into(),
                to: "0.9.3".into()
            })
        );
        assert_eq!(
            plan("0.9.3", "v0.9.3", true),
            Ok(Plan::UpToDate {
                current: "0.9.3".into()
            })
        );
    }

    #[test]
    fn a_non_semver_tag_is_an_error() {
        assert!(plan("0.10.0", "nightly", false).is_err());
    }

    #[test]
    fn without_keys_no_signature_is_required() {
        for (target, first) in [
            ("0.12.0", Some("0.11.0")),
            ("0.11.0", Some("0.11.0")),
            ("0.9.0", Some("0.11.0")),
            ("0.12.0", None),
        ] {
            assert_eq!(
                signature_required(target, first, false),
                Ok(false),
                "{target} with first signed {first:?}"
            );
        }
    }

    #[test]
    fn keys_without_a_first_signed_release_require_nothing() {
        assert_eq!(signature_required("0.12.0", None, true), Ok(false));
        assert_eq!(signature_required("v0.12.0", None, true), Ok(false));
    }

    #[test]
    fn the_first_signed_release_and_later_ones_require_a_signature() {
        let first = Some("0.11.0");
        assert_eq!(signature_required("0.11.0", first, true), Ok(true));
        assert_eq!(signature_required("v0.11.0", first, true), Ok(true));
        assert_eq!(signature_required("0.11.1", first, true), Ok(true));
        assert_eq!(signature_required("v1.0.0", first, true), Ok(true));
        // A `v` on the threshold is the same release.
        assert_eq!(
            signature_required("0.11.0", Some("v0.11.0"), true),
            Ok(true)
        );
    }

    #[test]
    fn releases_before_the_first_signed_one_are_checksum_only() {
        let first = Some("0.11.0");
        assert_eq!(signature_required("0.10.1", first, true), Ok(false));
        assert_eq!(signature_required("v0.10.1", first, true), Ok(false));
        // A pre-release of the first signed version sorts before it.
        assert_eq!(signature_required("0.11.0-rc.1", first, true), Ok(false));
    }

    #[test]
    fn a_non_semver_version_is_an_error_when_signing_is_on() {
        assert!(signature_required("nightly", Some("0.11.0"), true).is_err());
        assert!(signature_required("0.11.0", Some("next"), true).is_err());
    }

    #[test]
    fn the_shipped_key_set_and_threshold_agree() {
        // Both are set in the same commit (docs/SELF_UPDATE.md): a threshold
        // with no key would never check a signature, and a key with no
        // threshold would never be used.
        assert_eq!(
            FIRST_SIGNED_RELEASE.is_some(),
            !RELEASE_KEYS.is_empty(),
            "set FIRST_SIGNED_RELEASE and RELEASE_KEYS together"
        );
        if let Some(first) = FIRST_SIGNED_RELEASE {
            // The threshold is semver and carries no `v`. It is set to the
            // next release, before `Cargo.toml` is bumped, so it is not
            // compared with this build's version.
            assert!(!first.starts_with('v'), "write {first} without the v");
            assert_eq!(signature_required(first, Some(first), true), Ok(true));
        }
    }

    /// ZIP-16 (#639): the binary swap must never install a link or a
    /// special file. `self_update`'s zip path refuses a symlink entry, but
    /// its tar path hands the entry to `tar`'s `unpack_in`, which restores
    /// a symlink as a real link whose target the crate does not confine to
    /// the staging dir — a crafted release could install any path as the
    /// new binary. The extracted path is checked with `symlink_metadata`
    /// (not `metadata`, which follows the link).
    #[test]
    fn a_special_extracted_binary_is_refused_before_the_swap() {
        let dir = tempfile::tempdir().unwrap();
        let regular = dir.path().join("jubarte");
        std::fs::write(&regular, b"binary").unwrap();
        extracted_binary_is_regular_file(&regular).expect("a regular file installs");
        extracted_binary_is_regular_file(dir.path())
            .expect_err("a directory at the extracted path must be refused");
        #[cfg(unix)]
        {
            let link = dir.path().join("linked");
            std::os::unix::fs::symlink(&regular, &link).unwrap();
            extracted_binary_is_regular_file(&link)
                .expect_err("a symlink at the extracted path must be refused");
            let dangling = dir.path().join("dangling");
            std::os::unix::fs::symlink(dir.path().join("no-such-target"), &dangling).unwrap();
            extracted_binary_is_regular_file(&dangling)
                .expect_err("a dangling symlink must be refused too");
        }
    }

    const UPDATE_MEMBER: &str = "jubarte-9.9.9-windows-x86_64/jubarte.exe";

    fn write_update_archive(dir: &std::path::Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, bytes).unwrap();
        path
    }

    fn deflated_update_zip(member: &str, payload: &[u8]) -> Vec<u8> {
        use std::io::Write;
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options: zip::write::FullFileOptions<'_, '_> =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        writer.start_file(member, options).expect("start member");
        writer.write_all(payload).expect("write member");
        writer.finish().expect("finish zip").into_inner()
    }

    /// ZIP-28 (#656): the downloaded file itself has a byte budget, before
    /// any member is inflated.
    #[test]
    fn update_archive_over_the_download_budget_is_refused() {
        let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let budget = (bytes.len() as u64).saturating_sub(1);
        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
            .expect_err("an archive larger than the download budget was accepted");
        assert!(
            err.contains("download budget"),
            "the refusal must name the download budget, got {err}"
        );
    }

    /// ZIP-28 (#656): the expected member can inflate far past the archive
    /// that carried it. The download fits; the unpacked member must not.
    #[test]
    fn update_archive_inflation_is_capped() {
        let payload = vec![0u8; 8_000];
        let bytes = deflated_update_zip(UPDATE_MEMBER, &payload);
        assert!(
            bytes.len() < payload.len(),
            "the fixture must be smaller on disk than the member it inflates to, got {} bytes",
            bytes.len()
        );
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let budget = bytes.len() as u64;
        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
            .expect_err("an inflated member past the budget was extracted with no cap");
        assert!(
            err.contains("inflates past"),
            "the refusal must name the inflation cap, got {err}"
        );
        assert_eq!(
            std::fs::read_dir(dir.path()).unwrap().count(),
            1,
            "a refused archive must stay the only file in the directory"
        );
    }

    /// ZIP-28 (#656): two central-directory entries with the expected name
    /// are ambiguous. The first match must not be installed.
    #[test]
    fn update_archive_duplicate_member_is_refused() {
        let name = UPDATE_MEMBER.as_bytes();
        let bytes = crate::admission::zip_names::zip(&[
            crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
            crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
        ]);
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("an archive that lists the expected member twice was accepted");
        assert!(
            err.contains("more than once"),
            "the refusal must name the repeated member, got {err}"
        );
    }

    /// #2084 review: a zipsign-signed zip starts with its
    /// signature block, not `PK`, and its offsets are not rewritten; zip and
    /// self_update still read it. The checks must run on it too.
    fn prefixed(prefix_len: usize, zip: &[u8]) -> Vec<u8> {
        let mut out = vec![0xA5u8; prefix_len];
        out.extend_from_slice(zip);
        out
    }

    #[test]
    fn update_archive_with_a_prefix_still_refuses_a_repeated_member() {
        let name = UPDATE_MEMBER.as_bytes();
        let bytes = prefixed(
            64,
            &crate::admission::zip_names::zip(&[
                crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
                crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
            ]),
        );
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a prefixed archive skipped the repeated-member check");
        assert!(err.contains("more than once"), "{err}");
    }

    #[test]
    fn update_archive_with_a_prefix_still_caps_inflation() {
        let payload = vec![0u8; 8_000];
        let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, &payload));
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let budget = bytes.len() as u64;
        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
            .expect_err("a prefixed archive skipped the inflation cap");
        assert!(err.contains("inflates past"), "{err}");
    }

    #[test]
    fn update_archive_with_a_prefix_and_one_member_is_allowed() {
        let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte"));
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("a signed (prefixed) release zip with one member");
    }

    /// #2084 review: zip names an entry by its adopted 0x7075
    /// Unicode Path, so a second entry whose raw name differs but whose
    /// Unicode Path is the member is the same installed file.
    #[test]
    fn update_archive_unicode_path_copy_is_a_repeated_member() {
        let name = UPDATE_MEMBER.as_bytes();
        let bytes = crate::admission::zip_names::zip(&[
            crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
            crate::admission::zip_names::RawEntry::raw(b"decoy.bin", b"SECOND").unicode_path(name),
        ]);
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a Unicode Path copy of the member was not counted");
        assert!(err.contains("more than once"), "{err}");
    }

    #[test]
    fn update_archive_single_member_is_allowed() {
        let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("one member inside the budget is the release zip");
    }

    #[test]
    fn update_archive_non_zip_inside_budget_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.tar.gz", b"not a zip");
        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("a tar.gz inside the download budget is not a zip refusal");
    }

    const TAR_MEMBER: &str = "jubarte-9.9.9-linux-x86_64/jubarte";

    /// A ustar header. `size` is the entry payload. Symlinks and hardlinks
    /// use a zero size and carry the target in the link field.
    fn tar_header(name: &str, typeflag: u8, mode: u32, size: u64, link: &str) -> [u8; 512] {
        let mut header = [0u8; 512];
        let name_bytes = name.as_bytes();
        assert!(name_bytes.len() < 100, "tar name fits the ustar field");
        header[..name_bytes.len()].copy_from_slice(name_bytes);
        let mode_text = format!("{mode:07o}");
        header[100..100 + mode_text.len()].copy_from_slice(mode_text.as_bytes());
        let size_text = format!("{size:011o}");
        header[124..124 + size_text.len()].copy_from_slice(size_text.as_bytes());
        header[136..147].copy_from_slice(b"00000000000");
        header[156] = typeflag;
        let link_bytes = link.as_bytes();
        assert!(
            link_bytes.len() < 100,
            "tar link target fits the ustar field"
        );
        header[157..157 + link_bytes.len()].copy_from_slice(link_bytes);
        header[257..263].copy_from_slice(b"ustar\0");
        header[263..265].copy_from_slice(b"00");
        tar_reseal(&mut header);
        header
    }

    /// Rewrite the header checksum after a test edits a field.
    fn tar_reseal(header: &mut [u8; 512]) {
        let mut sum = 0u32;
        for (index, byte) in header.iter().enumerate() {
            if (148..156).contains(&index) {
                sum += u32::from(b' ');
            } else {
                sum += u32::from(*byte);
            }
        }
        let checksum = format!("{sum:06o}\0 ");
        header[148..156].copy_from_slice(checksum.as_bytes());
    }

    /// One PAX extended-header record, `"<len> <key>=<value>\n"`, where
    /// `<len>` counts the whole record including its own digits.
    fn pax_record(key: &str, value: &str) -> Vec<u8> {
        let body = format!(" {key}={value}\n");
        let mut len = body.len() + 1;
        while format!("{len}").len() + body.len() != len {
            len += 1;
        }
        format!("{len}{body}").into_bytes()
    }

    fn gzip_tar(entries: &[([u8; 512], &[u8])]) -> Vec<u8> {
        use std::io::Write;
        let mut raw = Vec::new();
        for (header, body) in entries {
            raw.extend_from_slice(header);
            raw.extend_from_slice(body);
            let pad = (512 - (body.len() % 512)) % 512;
            raw.extend(std::iter::repeat_n(0u8, pad));
        }
        raw.extend_from_slice(&[0u8; 1024]);
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&raw).expect("gzip");
        encoder.finish().expect("finish gzip")
    }

    fn tar_archive(dir: &std::path::Path, entries: &[([u8; 512], &[u8])]) -> std::path::PathBuf {
        write_update_archive(dir, "jubarte.tar.gz", &gzip_tar(entries))
    }

    /// R06a (#1305): macOS and Linux extract a tar.gz. A symlink at the
    /// binary's path must not be unpacked and installed.
    #[test]
    fn update_tar_symlink_member_is_refused() {
        let header = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &[][..])]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a tar.gz symlink member was accepted");
        assert!(
            err.contains("symlink"),
            "the refusal must name the symlink, got {err}"
        );
    }

    /// R06a (#1305): a hardlink is not a regular file either.
    #[test]
    fn update_tar_hardlink_member_is_refused() {
        let header = tar_header(TAR_MEMBER, b'1', 0o644, 0, "other");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &[][..])]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a tar.gz hardlink member was accepted");
        assert!(
            err.contains("hardlink"),
            "the refusal must name the hardlink, got {err}"
        );
    }

    /// R06a (#1305): the zip arm masks mode to `0o777`. A setuid tar member
    /// must not be installed with those bits.
    #[test]
    fn update_tar_setuid_member_is_refused() {
        let body = b"#!/jubarte";
        let header = tar_header(TAR_MEMBER, b'0', 0o4755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a setuid tar member was accepted");
        assert!(
            err.contains("setuid"),
            "the refusal must name the setuid bit, got {err}"
        );
    }

    /// R06a (#1305): an entry name that climbs out of the extract directory
    /// is refused even when the expected binary is also present.
    #[test]
    fn update_tar_escaping_entry_is_refused() {
        let body = b"#!/jubarte";
        let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let escape = tar_header("../outside", b'0', 0o644, 1, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a tar entry that climbs out of the extract directory was accepted");
        assert!(
            err.contains("escapes"),
            "the refusal must name the escaping path, got {err}"
        );
    }

    /// #2085 review: the tar crate takes a member's path from a PAX `path`
    /// record before the ustar name. A symlink whose ustar name is harmless
    /// but whose PAX path is the binary must be refused.
    #[test]
    fn update_tar_pax_path_symlink_is_refused() {
        let body = b"#!/jubarte";
        let pax = pax_record("path", TAR_MEMBER);
        let pax_header = tar_header("PaxHeaders/other", b'x', 0o644, pax.len() as u64, "");
        let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(
            dir.path(),
            &[(pax_header, &pax[..]), (link, &[][..]), (decoy, &body[..])],
        );
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a symlink named by a PAX path record was accepted");
        assert!(err.contains("symlink"), "got {err}");
    }

    /// #2085 review: a GNU `L` long-name entry renames the member after it.
    #[test]
    fn update_tar_gnu_long_name_symlink_is_refused() {
        let body = b"#!/jubarte";
        let mut long = TAR_MEMBER.as_bytes().to_vec();
        long.push(0);
        let long_header = tar_header("././@LongLink", b'L', 0o644, long.len() as u64, "");
        let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(
            dir.path(),
            &[
                (long_header, &long[..]),
                (link, &[][..]),
                (decoy, &body[..]),
            ],
        );
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a symlink named by a GNU long name was accepted");
        assert!(err.contains("symlink"), "got {err}");
    }

    /// #2085 review: a PAX `size` record overrides the ustar size. A gate
    /// that skips the ustar size steps over a header the extractor reads.
    #[test]
    fn update_tar_pax_size_cannot_hide_a_member() {
        let body = b"#!/jubarte";
        let pax = pax_record("size", "0");
        let pax_header = tar_header("PaxHeaders/pad", b'x', 0o644, pax.len() as u64, "");
        let hidden = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
        let pad = tar_header("pad", b'0', 0o644, 512, "");
        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(
            dir.path(),
            &[
                (pax_header, &pax[..]),
                (pad, &hidden[..]),
                (decoy, &body[..]),
            ],
        );
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a member hidden behind a PAX size was accepted");
        assert!(err.contains("symlink"), "got {err}");
    }

    /// #2085 review: the tar crate trims blanks around an octal field, so a
    /// mode of `" 4755"` is setuid there and must be setuid here.
    #[test]
    fn update_tar_space_led_setuid_mode_is_refused() {
        let body = b"#!/jubarte";
        let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        header[100..108].copy_from_slice(b"  4755\0\0");
        tar_reseal(&mut header);
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a blank-led setuid mode was accepted");
        assert!(err.contains("setuid"), "got {err}");
    }

    /// #2093 review: the tar crate cuts a numeric field at its first NUL
    /// and refuses what is left when it is empty. A NUL-led size must not
    /// read as zero here, or the gate and the extractor walk different
    /// entries.
    #[test]
    fn update_tar_nul_led_size_is_refused() {
        let body = b"#!/jubarte";
        let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        header[124..136].copy_from_slice(b"\x0000000000012");
        tar_reseal(&mut header);
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a NUL-led size field was accepted");
        assert!(err.contains("octal"), "got {err}");
    }

    /// #2085 review: a `..` between backslashes is refused like one
    /// between slashes, matching how member names are compared.
    #[test]
    fn update_tar_backslash_parent_entry_is_refused() {
        let body = b"#!/jubarte";
        let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let escape = tar_header("jubarte-9.9.9\\..\\..\\outside", b'0', 0o644, 1, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect_err("a backslash .. entry was accepted");
        assert!(err.contains("escapes"), "got {err}");
    }

    /// A long binary path carried by a PAX record (as GNU tar and bsdtar
    /// write it) is still the release archive.
    #[test]
    fn update_tar_pax_path_regular_member_is_allowed() {
        let body = b"#!/jubarte";
        let mut pax = pax_record("mtime", "1700000000.5");
        pax.extend(pax_record("path", TAR_MEMBER));
        let pax_header = tar_header("PaxHeaders/jubarte", b'x', 0o644, pax.len() as u64, "");
        let binary = tar_header("short-name", b'0', 0o755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(pax_header, &pax[..]), (binary, &body[..])]);
        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("a regular member named by a PAX path is the release archive");
    }

    #[test]
    fn update_tar_regular_member_is_allowed() {
        let body = b"#!/jubarte";
        let header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("a regular tar member inside the budget is the release archive");
        let fixture = dir.path().join("unsigned.tar.gz");
        std::fs::write(
            &fixture,
            include_bytes!("../../../tests/data/self_update/unsigned.tar.gz"),
        )
        .unwrap();
        confine_update_zip(&fixture, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("the signed-update fixture tar is a regular member");
    }

    fn gzip_raw(raw: &[u8]) -> Vec<u8> {
        use std::io::Write;
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(raw).expect("gzip");
        encoder.finish().expect("finish gzip")
    }

    fn confine_tar(entries: &[([u8; 512], &[u8])], budget: u64) -> Result<(), String> {
        let dir = tempfile::tempdir().unwrap();
        let archive = tar_archive(dir.path(), entries);
        confine_update_zip(&archive, TAR_MEMBER, budget)
    }

    fn confine_raw(raw: &[u8]) -> Result<(), String> {
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.tar.gz", &gzip_raw(raw));
        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
    }

    fn gnu(mut header: [u8; 512]) -> [u8; 512] {
        header[257..263].copy_from_slice(b"ustar ");
        header[263..265].copy_from_slice(b" \0");
        tar_reseal(&mut header);
        header
    }

    #[test]
    fn update_tar_header_damage_is_refused() {
        let mut bad = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
        bad[148] ^= 1;
        let err = confine_tar(&[(bad, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert_eq!(err, "update archive is not a tar");
        let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
        let err = confine_raw(&header[..100]).unwrap_err();
        assert_eq!(err, "update archive ended inside a tar header");
        let big = tar_header(TAR_MEMBER, b'0', 0o755, 600, "");
        let mut raw = big.to_vec();
        raw.extend_from_slice(&[7u8; 100]);
        assert_eq!(
            confine_raw(&raw).unwrap_err(),
            "update archive ended inside a tar member"
        );
        // The budget runs out inside the header, then inside the body.
        for budget in [200, 520] {
            let err = confine_tar(&[(header, &b"x"[..])], budget).unwrap_err();
            assert!(
                err.contains(&format!("inflates past the {budget}-byte budget")),
                "{err}"
            );
        }
    }

    #[test]
    fn update_tar_member_count_must_be_one() {
        let member = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
        let err = confine_tar(
            &[(member, &b"x"[..]), (member, &b"x"[..])],
            UPDATE_ARCHIVE_BYTE_BUDGET,
        )
        .unwrap_err();
        assert!(err.contains("more than once"), "{err}");
        let other = tar_header("README", b'0', 0o644, 1, "");
        let err = confine_tar(&[(other, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("has no member"), "{err}");
    }

    #[test]
    fn update_tar_long_names_name_the_next_member_once() {
        let long_body = format!("{TAR_MEMBER}\0");
        let long = gnu(tar_header(
            "././@LongLink",
            b'L',
            0o644,
            long_body.len() as u64,
            "",
        ));
        let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
        confine_tar(
            &[(long, long_body.as_bytes()), (plain, &b"x"[..])],
            UPDATE_ARCHIVE_BYTE_BUDGET,
        )
        .expect("a GNU long name naming the member is the member");
        let err = confine_tar(
            &[
                (long, long_body.as_bytes()),
                (long, long_body.as_bytes()),
                (plain, &b"x"[..]),
            ],
            UPDATE_ARCHIVE_BYTE_BUDGET,
        )
        .unwrap_err();
        assert!(err.contains("one member twice"), "{err}");
        let err =
            confine_tar(&[(long, long_body.as_bytes())], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("never follows"), "{err}");
        let huge = tar_header("././@LongLink", b'L', 0o644, TAR_EXTENSION_LIMIT + 1, "");
        let err = confine_tar(&[(huge, &b""[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("exceeds"), "{err}");
        // Without a recognised magic an `L` entry is an ordinary member.
        let mut unmarked = tar_header("././@LongLink", b'L', 0o644, long_body.len() as u64, "");
        unmarked[257..265].fill(0);
        tar_reseal(&mut unmarked);
        let err = confine_tar(
            &[(unmarked, long_body.as_bytes())],
            UPDATE_ARCHIVE_BYTE_BUDGET,
        )
        .unwrap_err();
        assert!(err.contains("has no member"), "{err}");
    }

    #[test]
    fn update_tar_ustar_prefix_joins_the_name() {
        let (prefix, name) = TAR_MEMBER.split_once('/').unwrap();
        let mut header = tar_header(name, b'0', 0o755, 1, "");
        header[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes());
        tar_reseal(&mut header);
        confine_tar(&[(header, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET)
            .expect("prefix/name is the member");
        let absolute = tar_header("/etc/jubarte", b'0', 0o755, 1, "");
        let err = confine_tar(&[(absolute, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("escapes"), "{err}");
        assert!(tar_name_escapes("\\jubarte"));
        assert!(!tar_name_escapes("dir/jubarte"));
    }

    #[test]
    fn tar_fields_parse_as_the_tar_crate_reads_them() {
        assert_eq!(tar_octal(b" +17 \0junk"), Ok(15));
        assert!(tar_octal(b"   \0").is_err());
        assert!(tar_octal(b"9").is_err());
        assert!(tar_octal(b"7777777777777777777777777").is_err());
        assert_eq!(pax_value(&pax_record("path", "a"), b"size"), Ok(None));
        assert_eq!(
            pax_value(b"x", b"path").unwrap_err(),
            "update archive PAX header is malformed"
        );
        assert!(pax_value(b"9 path\n", b"path").is_err());
    }

    fn stored_zip(members: &[&str], comment: &str) -> Vec<u8> {
        use std::io::Write;
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options: zip::write::FullFileOptions<'_, '_> =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
        for member in members {
            if let Some(dir) = member.strip_suffix('/') {
                writer
                    .add_directory(dir, options.clone())
                    .expect("directory");
            } else {
                writer
                    .start_file(*member, options.clone())
                    .expect("start member");
                writer.write_all(b"binary").expect("write member");
            }
        }
        writer.set_comment(comment).unwrap();
        writer.finish().expect("finish zip").into_inner()
    }

    fn confine_bytes(bytes: &[u8]) -> Result<(), String> {
        let dir = tempfile::tempdir().unwrap();
        let archive = write_update_archive(dir.path(), "jubarte.zip", bytes);
        confine_update_zip(&archive, "jubarte.exe", UPDATE_ARCHIVE_BYTE_BUDGET)
    }

    /// Offset of the end record in a zip written without a comment.
    fn eocd(bytes: &[u8]) -> usize {
        bytes.len() - 22
    }

    fn central(bytes: &[u8]) -> usize {
        let at = eocd(bytes);
        u32::from_le_bytes(bytes[at + 16..at + 20].try_into().unwrap()) as usize
    }

    #[test]
    fn update_zip_directory_damage_is_refused() {
        let good = stored_zip(&["bin/", "jubarte.exe"], "");
        confine_bytes(&good).expect("one regular member");
        // A comment after the end record still finds it.
        confine_bytes(&stored_zip(&["jubarte.exe"], "signed by nobody")).expect("commented zip");

        let mut zip64 = good.clone();
        let at = eocd(&zip64);
        zip64[at + 10..at + 12].copy_from_slice(&u16::MAX.to_le_bytes());
        assert!(confine_bytes(&zip64).unwrap_err().contains("ZIP64"));

        let mut count = good.clone();
        let at = eocd(&count);
        count[at + 10..at + 12].copy_from_slice(&3u16.to_le_bytes());
        assert!(
            confine_bytes(&count)
                .unwrap_err()
                .contains("does not match its end record")
        );

        let mut torn = good.clone();
        let cd = central(&torn);
        torn[cd] = b'X';
        assert!(
            confine_bytes(&torn)
                .unwrap_err()
                .contains("central directory is truncated")
        );

        let mut long = good.clone();
        let cd = central(&long);
        long[cd + 28..cd + 30].copy_from_slice(&u16::MAX.to_le_bytes());
        assert!(
            confine_bytes(&long)
                .unwrap_err()
                .contains("runs past the directory")
        );

        let mut empty = vec![0x50, 0x4b, 0x05, 0x06];
        empty.extend_from_slice(&[0u8; 18]);
        assert!(confine_bytes(&empty).unwrap_err().contains("has no member"));
    }

    #[test]
    fn update_files_that_are_not_zips_are_told_apart() {
        let err = confine_bytes(b"PK\x03\x04 not really a zip").unwrap_err();
        assert_eq!(err, "update archive has no zip end record");
        confine_bytes(b"P").expect("a one-byte file is no archive this gate knows");
        assert!(member_names_match(b"./bin\\jubarte", "bin/jubarte"));
        assert!(!member_names_match(b"bin/", "bin/"));
        assert!(!member_names_match(b"bin/jubartf", "bin/jubarte"));
    }

    #[test]
    fn update_tar_extensions_left_dangling_or_unterminated() {
        let long = gnu(tar_header(
            "././@LongLink",
            b'L',
            0o644,
            TAR_MEMBER.len() as u64,
            "",
        ));
        let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
        confine_tar(
            &[(long, TAR_MEMBER.as_bytes()), (plain, &b"x"[..])],
            UPDATE_ARCHIVE_BYTE_BUDGET,
        )
        .expect("a long name without its NUL still names the member");
        let link = gnu(tar_header("././@LongLink", b'K', 0o644, 4, ""));
        let err = confine_tar(&[(link, &b"dest"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("never follows"), "{err}");
        let records = pax_record("comment", "x");
        let pax = tar_header("pax", b'x', 0o644, records.len() as u64, "");
        let err = confine_tar(&[(pax, &records[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
        assert!(err.contains("never follows"), "{err}");
        // An archive that stops at a block boundary, with no end blocks.
        let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
        let mut raw = header.to_vec();
        raw.extend_from_slice(&[b'x'; 512]);
        confine_raw(&raw).expect("a clean end after a whole member");
    }

    #[test]
    fn update_zip_end_records_hidden_or_impossible() {
        // A comment holding an end-record signature is skipped over.
        let fake = format!("PK\u{5}\u{6}{}", "z".repeat(30));
        confine_bytes(&stored_zip(&["jubarte.exe"], &fake)).expect("the real end record is found");
        let good = stored_zip(&["jubarte.exe"], "");
        for field in [12, 16] {
            let mut zip64 = good.clone();
            let at = eocd(&zip64);
            zip64[at + field..at + field + 4].copy_from_slice(&u32::MAX.to_le_bytes());
            assert!(
                confine_bytes(&zip64).unwrap_err().contains("ZIP64"),
                "{field}"
            );
        }
        // A nameless entry whose comment holds the old name's bytes.
        let mut nameless = good.clone();
        let cd = central(&nameless);
        let name_len = nameless[cd + 28..cd + 30].to_vec();
        nameless[cd + 28..cd + 30].copy_from_slice(&[0, 0]);
        nameless[cd + 30..cd + 32].copy_from_slice(&[0, 0]);
        nameless[cd + 32..cd + 34].copy_from_slice(&name_len);
        assert!(
            confine_bytes(&nameless)
                .unwrap_err()
                .contains("has no member")
        );
    }
}