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
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
/*!
Amazon S3 releases
*/
use crate::backends::common::{CommonBuilderConfig, CommonConfig, RequestConfig};
use crate::backends::send;
use crate::http_client::HttpResponse;
use crate::{
errors::*,
update::{Release, ReleaseAsset, ReleaseUpdate, Releases},
version::bump_is_greater,
};
use log::debug;
use quick_xml::events::Event;
use quick_xml::Reader;
use regex::Regex;
use std::cmp::Ordering;
use std::path::PathBuf;
/// Maximum number of items to retrieve from S3 API
const MAX_KEYS: u8 = 100;
/// Re-export the S3 [`AccessKey`] credential type at the backend module level so consumers can
/// name it as `self_update::backends::s3::AccessKey` (e.g. to build one explicitly). Available
/// under the `s3-auth` feature.
#[cfg(feature = "s3-auth")]
pub use auth::AccessKey;
/// The service end point.
///
#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub enum EndPoint {
/// Short for `https://<bucket>.s3.<region>.amazonaws.com/`
#[default]
S3,
/// Short for `https://<bucket>.s3.dualstack.<region>.amazonaws.com/`
S3DualStack,
/// Short for `https://storage.googleapis.com/<bucket>/`
GCS,
/// Short for `https://<bucket>.<region>.digitaloceanspaces.com/`
DigitalOceanSpaces,
/// Generic, for other s3 compatible providers
Generic {
/// The full URL of the end point. For example:
///
/// - `https://bucket.s3.example.com/`
/// - `https://s3.example.com/bucket/`
end_point: String,
},
}
impl From<&str> for EndPoint {
fn from(value: &str) -> Self {
Self::Generic {
end_point: value.to_owned(),
}
}
}
impl From<String> for EndPoint {
fn from(value: String) -> Self {
Self::Generic { end_point: value }
}
}
/// Whether `end_point` needs a `region` to form its URL. The AWS-family endpoints embed the region
/// in the host; `GCS` and `Generic` do not use it.
fn endpoint_requires_region(end_point: &EndPoint) -> bool {
matches!(
end_point,
EndPoint::S3 | EndPoint::S3DualStack | EndPoint::DigitalOceanSpaces
)
}
/// Validate the endpoint/region pairing at build time so a missing `region` is reported from
/// `build()` (like every other required field) rather than at the first network call.
fn check_endpoint_region(end_point: &EndPoint, region: &Option<String>) -> Result<()> {
if endpoint_requires_region(end_point) && region.is_none() {
bail!(
Error::Config,
"`region` required for the S3, S3DualStack, and DigitalOceanSpaces endpoints; call `.region(...)`"
);
}
Ok(())
}
/// `ReleaseList` Builder
#[derive(Clone, Debug)]
#[must_use]
pub struct ReleaseListBuilder {
end_point: EndPoint,
bucket_name: Option<String>,
asset_prefix: Option<String>,
target: Option<String>,
region: Option<String>,
#[cfg(feature = "s3-auth")]
access_key: Option<auth::AccessKey>,
request: RequestConfig,
}
impl ReleaseListBuilder {
/// Set the bucket name, used to build an S3 api url
pub fn bucket_name(&mut self, name: impl Into<String>) -> &mut Self {
self.bucket_name = Some(name.into());
self
}
/// Set an optional S3 key prefix, sent as the `prefix=` parameter of the bucket listing.
///
/// This scopes the listing to keys under that prefix (e.g. a subdirectory) on the S3 side; it
/// is **not** a client-side filter of asset file names (for that, see
/// [`filter_target`](Self::filter_target)). The prefix is stripped from the returned names, so a
/// `releases/` prefix lets you keep assets in a subdirectory.
pub fn asset_prefix(&mut self, prefix: impl Into<String>) -> &mut Self {
self.asset_prefix = Some(prefix.into());
self
}
/// Set the S3 region embedded in the endpoint host.
///
/// Required for the `S3`, `S3DualStack`, and `DigitalOceanSpaces` endpoints (it is part of
/// their hostname) and validated by [`build`](Self::build). Ignored by `GCS` and `Generic`
/// endpoints, which carry no region in the URL (under `s3-auth`, SigV4 still defaults the
/// signing region to `us-east-1` when none is set).
pub fn region(&mut self, region: impl Into<String>) -> &mut Self {
self.region = Some(region.into());
self
}
/// Set the end point
pub fn end_point(&mut self, end_point: impl Into<EndPoint>) -> &mut Self {
self.end_point = end_point.into();
self
}
/// Set the optional arch `target` name, used to filter the releases this list returns to those
/// carrying an asset whose name contains `target`.
///
/// This is the **`ReleaseList`** filter and differs from
/// [`Update::target`](UpdateBuilder::target): `filter_target` drops whole releases from the
/// listing when no asset matches, whereas the `Update` `target` selects *which asset* of the
/// chosen release to download.
pub fn filter_target(&mut self, target: impl Into<String>) -> &mut Self {
self.target = Some(target.into());
self
}
#[cfg(feature = "s3-auth")]
/// Set the access key
pub fn access_key(&mut self, access_key: impl Into<auth::AccessKey>) -> &mut Self {
self.access_key = Some(access_key.into());
self
}
/// S3 does not authenticate via bearer tokens; use `.access_key((id, secret))` under the
/// `s3-auth` feature instead. This is a no-op shim so that code ported from a git backend
/// gets a helpful deprecation hint rather than a bare "no method" error.
#[deprecated(
note = "s3 authenticates via `.access_key((id, secret))` under the `s3-auth` feature, not auth tokens"
)]
pub fn auth_token(&mut self, _token: impl Into<String>) -> &mut Self {
self
}
request_config_setters!(request);
/// Verify builder args, returning a `ReleaseList`
pub fn build(&self) -> Result<ReleaseList> {
self.request.check()?;
check_endpoint_region(&self.end_point, &self.region)?;
Ok(ReleaseList {
end_point: self.end_point.clone(),
bucket_name: if let Some(ref name) = self.bucket_name {
name.to_owned()
} else {
bail!(Error::Config, "`bucket_name` required")
},
region: self.region.clone(),
asset_prefix: self.asset_prefix.clone(),
target: self.target.clone(),
#[cfg(feature = "s3-auth")]
access_key: self.access_key.clone(),
request: self.request.clone(),
})
}
}
/// `ReleaseList` provides a builder api for querying an S3 bucket,
/// returning a `Vec` of available `Release`s
#[derive(Clone, Debug)]
pub struct ReleaseList {
end_point: EndPoint,
bucket_name: String,
asset_prefix: Option<String>,
target: Option<String>,
region: Option<String>,
#[cfg(feature = "s3-auth")]
access_key: Option<auth::AccessKey>,
request: RequestConfig,
}
impl ReleaseList {
/// Initialize a ReleaseListBuilder
pub fn configure() -> ReleaseListBuilder {
ReleaseListBuilder {
end_point: EndPoint::default(),
bucket_name: None,
asset_prefix: None,
target: None,
region: None,
#[cfg(feature = "s3-auth")]
access_key: None,
request: RequestConfig::default(),
}
}
/// Retrieve a list of `Release`s.
/// If specified, filter for those containing a specified `target`
pub fn fetch(&self) -> Result<Vec<Release>> {
let releases = fetch_releases_from_s3(
&self.end_point,
&self.bucket_name,
&self.region,
&self.asset_prefix,
#[cfg(feature = "s3-auth")]
&self.access_key,
&self.request,
)?;
let releases = match self.target {
None => releases,
Some(ref target) => releases
.into_iter()
.filter(|r| r.has_target_asset(target))
.collect::<Vec<_>>(),
};
Ok(releases)
}
}
/// `s3::Update` builder
///
/// Configure download and installation from
/// `https://<bucket_name>.s3.<region>.amazonaws.com/<asset filename>`
#[derive(Clone, Debug, Default)]
#[must_use]
pub struct UpdateBuilder {
end_point: EndPoint,
bucket_name: Option<String>,
asset_prefix: Option<String>,
region: Option<String>,
#[cfg(feature = "s3-auth")]
access_key: Option<auth::AccessKey>,
common: CommonBuilderConfig,
}
/// Configure download and installation from bucket
impl UpdateBuilder {
/// Initialize a new builder
pub fn new() -> Self {
Default::default()
}
/// Set the end point
pub fn end_point(&mut self, end_point: impl Into<EndPoint>) -> &mut Self {
self.end_point = end_point.into();
self
}
/// Set the bucket name, used to build a s3 api url
pub fn bucket_name(&mut self, name: impl Into<String>) -> &mut Self {
self.bucket_name = Some(name.into());
self
}
/// Set an optional S3 key prefix, sent as the `prefix=` parameter of the bucket listing.
///
/// This scopes the listing to keys under that prefix (e.g. a subdirectory) on the S3 side; it
/// is **not** a client-side filter of asset file names. The prefix is stripped from the
/// returned names, so a `releases/` prefix lets you keep assets in a subdirectory.
pub fn asset_prefix(&mut self, prefix: impl Into<String>) -> &mut Self {
self.asset_prefix = Some(prefix.into());
self
}
/// Set the S3 region embedded in the endpoint host.
///
/// Required for the `S3`, `S3DualStack`, and `DigitalOceanSpaces` endpoints (it is part of
/// their hostname) and validated by [`build`](Self::build). Ignored by `GCS` and `Generic`
/// endpoints, which carry no region in the URL (under `s3-auth`, SigV4 still defaults the
/// signing region to `us-east-1` when none is set).
pub fn region(&mut self, region: impl Into<String>) -> &mut Self {
self.region = Some(region.into());
self
}
#[cfg(feature = "s3-auth")]
/// Set the access key (an `(access_key_id, secret_access_key)` pair)
pub fn access_key(&mut self, access_key: impl Into<auth::AccessKey>) -> &mut Self {
self.access_key = Some(access_key.into());
self
}
/// S3 does not authenticate via bearer tokens; use `.access_key((id, secret))` under the
/// `s3-auth` feature instead. This is a no-op shim so that code ported from a git backend
/// gets a helpful deprecation hint rather than a bare "no method" error.
#[deprecated(
note = "s3 authenticates via `.access_key((id, secret))` under the `s3-auth` feature, not auth tokens"
)]
pub fn auth_token(&mut self, _token: impl Into<String>) -> &mut Self {
self
}
impl_common_builder_setters!(no_auth_token);
fn build_update(&self) -> Result<Update> {
check_endpoint_region(&self.end_point, &self.region)?;
Ok(Update {
end_point: self.end_point.clone(),
bucket_name: if let Some(ref name) = self.bucket_name {
name.to_owned()
} else {
bail!(Error::Config, "`bucket_name` required")
},
region: self.region.clone(),
#[cfg(feature = "s3-auth")]
access_key: self.access_key.clone(),
asset_prefix: self.asset_prefix.clone(),
common: self.common.build()?,
})
}
/// Confirm config and create a ready-to-use `Update`
///
/// * Errors:
/// * Config - Invalid `Update` configuration
pub fn build(&self) -> Result<Box<dyn ReleaseUpdate>> {
Ok(Box::new(self.build_update()?))
}
/// Confirm config and create a ready-to-use `Update` for the async API (`update_async`).
///
/// Unlike [`build`](Self::build) this returns the concrete `Update` (not a
/// `Box<dyn ReleaseUpdate>`) so the inherent `*_async` methods are reachable.
#[cfg(feature = "async")]
pub fn build_async(&self) -> Result<Update> {
self.build_update()
}
}
#[cfg(feature = "async")]
impl Update {
impl_async_update_methods!();
}
/// Updates to a specified or latest release distributed via S3
#[derive(Debug)]
#[non_exhaustive]
pub struct Update {
end_point: EndPoint,
bucket_name: String,
asset_prefix: Option<String>,
region: Option<String>,
#[cfg(feature = "s3-auth")]
access_key: Option<auth::AccessKey>,
common: CommonConfig,
}
impl Update {
/// Initialize a new `Update` builder
pub fn configure() -> UpdateBuilder {
UpdateBuilder::new()
}
/// Fetch the bucket's releases (sync). Wraps the per-backend argument plumbing so the
/// `ReleaseUpdate` methods stay terse.
fn fetch_releases(&self) -> Result<Vec<Release>> {
fetch_releases_from_s3(
&self.end_point,
&self.bucket_name,
&self.region,
&self.asset_prefix,
#[cfg(feature = "s3-auth")]
&self.access_key,
&self.common.request,
)
}
/// Async sibling of [`fetch_releases`](Self::fetch_releases).
#[cfg(feature = "async")]
async fn fetch_releases_async(&self) -> Result<Vec<Release>> {
fetch_releases_from_s3_async(
&self.end_point,
&self.bucket_name,
&self.region,
&self.asset_prefix,
#[cfg(feature = "s3-auth")]
&self.access_key,
&self.common.request,
)
.await
}
}
/// Pick the single highest-version release. Shared by the sync and async paths.
fn pick_latest(releases: &[Release]) -> Result<Release> {
let rel = releases
.iter()
.max_by(|x, y| match bump_is_greater(&y.version, &x.version) {
Ok(is_greater) => {
if is_greater {
Ordering::Greater
} else {
Ordering::Less
}
}
// Ignoring release due to an unexpected failure in parsing its version string
Err(_) => Ordering::Less,
});
match rel {
Some(r) => Ok(r.clone()),
None => bail!(Error::Release, "No release was found"),
}
}
/// Filter releases newer than `current_version`, sorted newest-first (the orchestrator takes the
/// first compatible one). Shared by the sync and async paths.
fn sort_newer(releases: Vec<Release>, current_version: &str) -> Vec<Release> {
let mut releases = releases
.into_iter()
.filter(|r| bump_is_greater(current_version, &r.version).unwrap_or(false))
.collect::<Vec<_>>();
// Descending order (latest first), since the update code takes `.first()`.
releases.sort_by(|x, y| match bump_is_greater(&y.version, &x.version) {
Ok(is_greater) => {
if is_greater {
Ordering::Less
} else {
Ordering::Greater
}
}
// Ignoring release due to an unexpected failure in parsing its version string
Err(_) => Ordering::Greater,
});
releases
}
/// Find the release matching an explicit version. Shared by the sync and async paths.
fn find_version(releases: &[Release], ver: &str) -> Result<Release> {
match releases.iter().find(|x| x.version == ver) {
Some(r) => Ok(r.clone()),
None => bail!(
Error::Release,
"No release with version '{}' was found",
ver
),
}
}
impl crate::update::sealed::Sealed for Update {}
impl ReleaseUpdate for Update {
fn get_latest_release(&self) -> Result<Releases> {
let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
let release = pick_latest(&self.fetch_releases()?)?;
Ok(Releases::new(vec![release], current_version))
}
fn get_latest_releases(&self) -> Result<Releases> {
let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
let releases = sort_newer(self.fetch_releases()?, ¤t_version);
Ok(Releases::new(releases, current_version))
}
fn get_release_version(&self, ver: &str) -> Result<Release> {
find_version(&self.fetch_releases()?, ver)
}
}
impl_update_config_accessors!(Update);
#[cfg(feature = "async")]
impl crate::update::AsyncFetch for Update {
async fn get_latest_release_async(&self) -> Result<Releases> {
let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
let release = pick_latest(&self.fetch_releases_async().await?)?;
Ok(Releases::new(vec![release], current_version))
}
async fn get_latest_releases_async(&self) -> Result<Releases> {
let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
let releases = sort_newer(self.fetch_releases_async().await?, ¤t_version);
Ok(Releases::new(releases, current_version))
}
async fn get_release_version_async(&self, ver: &str) -> Result<Release> {
find_version(&self.fetch_releases_async().await?, ver)
}
}
/// Generate S3 auth parameters
#[cfg(feature = "s3-auth")]
mod auth {
use crate::errors::*;
use hmac::{Hmac, Mac};
use percent_encoding::{utf8_percent_encode, AsciiSet, PercentEncode, NON_ALPHANUMERIC};
use sha2::{Digest, Sha256};
use std::{
borrow::Cow,
time::{SystemTime, UNIX_EPOCH},
};
use time::OffsetDateTime;
use url::Url;
/// S3 access credentials used to sign requests (AWS SigV4) for private buckets.
///
/// Construct one with [`AccessKey::new`] or from an `(access_key_id, secret_access_key)` pair
/// via [`From`] (e.g. `("AKIA…", "secret").into()`), which is what
/// [`access_key`](super::UpdateBuilder::access_key) accepts. It is `#[non_exhaustive]` so future
/// credential fields (e.g. an STS session token) can be added without a breaking change; build
/// it through `new` or the `From` impls rather than a struct literal.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct AccessKey {
pub access_key_id: String,
pub secret_access_key: String,
}
impl AccessKey {
/// Construct an `AccessKey` from an access-key id and secret. Equivalent to the `From`
/// pair conversions, but discoverable as a named constructor (the type is
/// `#[non_exhaustive]`, so it can't be built with a struct literal from outside the crate).
pub fn new(access_key_id: impl Into<String>, secret_access_key: impl Into<String>) -> Self {
Self {
access_key_id: access_key_id.into(),
secret_access_key: secret_access_key.into(),
}
}
}
impl From<(&str, &str)> for AccessKey {
fn from(value: (&str, &str)) -> Self {
Self {
access_key_id: value.0.to_owned(),
secret_access_key: value.1.to_owned(),
}
}
}
impl From<(String, String)> for AccessKey {
fn from(value: (String, String)) -> Self {
Self {
access_key_id: value.0,
secret_access_key: value.1,
}
}
}
// NON_ALPHANUMERIC Encodes everything except A-Z, a-z, 0-9.
// Remove the last 4 reserved characters that AWS doesn't encode: - . _ ~
const URI_ENCODE: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
// AWS doesn't encode the slash character in the canonical URI, but it does
// encode it in query parameters
const URI_ENCODE_KEEP_SLASH: &AsciiSet = &URI_ENCODE.remove(b'/');
// Encode a string for use in AWS S3 signature v4, encoding reserved
// characters and optionally the slash character
fn uri_encode(input: &str, encode_slash: bool) -> PercentEncode<'_> {
let set = if encode_slash {
URI_ENCODE
} else {
URI_ENCODE_KEEP_SLASH
};
utf8_percent_encode(input, set)
}
fn hex_sha256(data: &[u8]) -> String {
let hash = Sha256::digest(data);
hash.iter().map(|b| format!("{b:02x}")).collect()
}
fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
let mut mac = Hmac::<Sha256>::new_from_slice(key)?;
mac.update(data);
Ok(mac.finalize().into_bytes().to_vec())
}
fn derive_signing_key(secret: &str, date_stamp: &str, region: &str) -> Result<Vec<u8>> {
let k_date = hmac_sha256(format!("AWS4{secret}").as_bytes(), date_stamp.as_bytes())?;
let k_region = hmac_sha256(&k_date, region.as_bytes())?;
let k_service = hmac_sha256(&k_region, b"s3")?;
hmac_sha256(&k_service, b"aws4_request")
}
fn format_timestamp(secs: u64) -> Result<(String, String)> {
let dt = OffsetDateTime::from_unix_timestamp(secs as i64)?;
let date_stamp = format!("{:04}{:02}{:02}", dt.year(), dt.month() as u8, dt.day());
let amz_date = format!(
"{date_stamp}T{:02}{:02}{:02}Z",
dt.hour(),
dt.minute(),
dt.second()
);
Ok((date_stamp, amz_date))
}
pub fn s3_signature_v4(
url_str: &str,
region: &Option<String>,
access_key: &Option<AccessKey>,
ttl_secs: u64,
) -> Result<String> {
let (access_key_id, secret_access_key) = match access_key {
Some(access_key) => (&access_key.access_key_id, &access_key.secret_access_key),
None => return Ok(url_str.to_owned()),
};
let url = Url::parse(url_str)?;
let host = url
.host_str()
.ok_or_else(|| Error::Config(format!("Cannot extract host from {:?}", url_str)))?;
let canonical_uri = if url.path().is_empty() {
"/"
} else {
url.path()
};
let now_secs = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let (date_stamp, amz_date) = format_timestamp(now_secs)?;
let region = region.as_deref().unwrap_or("us-east-1");
let credential_scope = format!("{date_stamp}/{region}/s3/aws4_request");
// Existing query params (decoded by url crate) + SigV4 params, sans Signature.
let mut params: Vec<_> = url.query_pairs().collect();
params.extend([
(
Cow::Borrowed("X-Amz-Algorithm"),
Cow::Borrowed("AWS4-HMAC-SHA256"),
),
(
Cow::Borrowed("X-Amz-Credential"),
Cow::Owned(format!("{access_key_id}/{credential_scope}")),
),
(Cow::Borrowed("X-Amz-Date"), Cow::Borrowed(&amz_date)),
(
Cow::Borrowed("X-Amz-Expires"),
Cow::Owned(ttl_secs.to_string()),
),
(Cow::Borrowed("X-Amz-SignedHeaders"), Cow::Borrowed("host")),
]);
params.sort_by(|a, b| a.0.cmp(&b.0));
let canonical_qs: String = params
.iter()
.map(|(k, v)| format!("{}={}", uri_encode(k, true), uri_encode(v, true)))
.collect::<Vec<_>>()
.join("&");
let canonical_request = format!(
"GET\n{}\n{canonical_qs}\nhost:{host}\n\nhost\nUNSIGNED-PAYLOAD",
uri_encode(canonical_uri, false),
);
let string_to_sign = format!(
"AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{}",
hex_sha256(canonical_request.as_bytes())
);
let signing_key = derive_signing_key(secret_access_key, &date_stamp, region)?;
let signature: String = hmac_sha256(&signing_key, string_to_sign.as_bytes())?
.iter()
.map(|b| format!("{b:02x}"))
.collect();
let base = &url_str[..url_str.find('?').unwrap_or(url_str.len())];
Ok(format!("{base}?{canonical_qs}&X-Amz-Signature={signature}"))
}
}
/// Build the S3 listing `api_url` and the `download_base_url` that asset URLs are formed against,
/// signing the listing URL when `s3-auth` is enabled. Shared by the sync and async fetch paths.
fn build_s3_api_url(
end_point: &EndPoint,
bucket_name: &str,
region: &Option<String>,
asset_prefix: &Option<String>,
#[cfg(feature = "s3-auth")] access_key: &Option<auth::AccessKey>,
) -> Result<(String, String)> {
let prefix = match asset_prefix {
Some(prefix) => format!("&prefix={}", prefix),
None => "".to_string(),
};
let region_result = region
.as_ref()
.ok_or_else(|| Error::Config("`region` required".to_string()));
let download_base_url = match end_point {
EndPoint::S3 => format!(
"https://{}.s3.{}.amazonaws.com/",
bucket_name, region_result?
),
EndPoint::S3DualStack => format!(
"https://{}.s3.dualstack.{}.amazonaws.com/",
bucket_name, region_result?
),
EndPoint::DigitalOceanSpaces => format!(
"https://{}.{}.digitaloceanspaces.com/",
bucket_name, region_result?
),
EndPoint::GCS => format!("https://storage.googleapis.com/{}/", bucket_name),
EndPoint::Generic { ref end_point } => end_point.clone(),
};
let api_url = match end_point {
EndPoint::S3
| EndPoint::S3DualStack
| EndPoint::DigitalOceanSpaces
| EndPoint::Generic { .. } => format!(
"{}?list-type=2&max-keys={}{}",
download_base_url, MAX_KEYS, prefix
),
EndPoint::GCS => format!("{}?max-keys={}{}", download_base_url, MAX_KEYS, prefix),
};
#[cfg(feature = "s3-auth")]
let api_url = auth::s3_signature_v4(&api_url, region, access_key, 300)?;
Ok((download_base_url, api_url))
}
/// Obtain list of releases from AWS S3 API, from bucket and region specified,
/// filtering assets which don't match the prefix string if provided.
///
/// This will strip the prefix from provided file names, allowing use with subdirectories
fn fetch_releases_from_s3(
end_point: &EndPoint,
bucket_name: &str,
region: &Option<String>,
asset_prefix: &Option<String>,
#[cfg(feature = "s3-auth")] access_key: &Option<auth::AccessKey>,
req: &RequestConfig,
) -> Result<Vec<Release>> {
let (download_base_url, api_url) = build_s3_api_url(
end_point,
bucket_name,
region,
asset_prefix,
#[cfg(feature = "s3-auth")]
access_key,
)?;
debug!("using api url: {:?}", api_url);
// `http_client::get` bails on any non-2xx status before returning the response.
let resp = send(&api_url, Default::default(), req)?;
let body = resp.text()?;
parse_s3_response(
&body,
&download_base_url,
#[cfg(feature = "s3-auth")]
region,
#[cfg(feature = "s3-auth")]
access_key,
)
}
/// Async sibling of [`fetch_releases_from_s3`], reusing [`build_s3_api_url`] and
/// [`parse_s3_response`] with the async transport.
#[cfg(feature = "async")]
async fn fetch_releases_from_s3_async(
end_point: &EndPoint,
bucket_name: &str,
region: &Option<String>,
asset_prefix: &Option<String>,
#[cfg(feature = "s3-auth")] access_key: &Option<auth::AccessKey>,
req: &RequestConfig,
) -> Result<Vec<Release>> {
use crate::backends::send_async;
let (download_base_url, api_url) = build_s3_api_url(
end_point,
bucket_name,
region,
asset_prefix,
#[cfg(feature = "s3-auth")]
access_key,
)?;
debug!("using api url: {:?}", api_url);
let resp = send_async(&api_url, Default::default(), req).await?;
let body = resp.text().await?;
parse_s3_response(
&body,
&download_base_url,
#[cfg(feature = "s3-auth")]
region,
#[cfg(feature = "s3-auth")]
access_key,
)
}
/// Parse an S3 `ListBucketResult` XML body into releases, forming (and, under `s3-auth`, signing)
/// each asset's download URL against `download_base_url`. Pure when `s3-auth` is off; under
/// `s3-auth` it signs each URL with a timestamped SigV4 signature and is therefore time-dependent.
/// Shared by both fetch paths.
fn parse_s3_response(
body: &str,
download_base_url: &str,
#[cfg(feature = "s3-auth")] region: &Option<String>,
#[cfg(feature = "s3-auth")] access_key: &Option<auth::AccessKey>,
) -> Result<Vec<Release>> {
let mut reader = Reader::from_str(body);
reader.config_mut().trim_text(true);
// Let's now parse the response to extract the releases
enum Tag {
Contents,
Key,
LastModified,
Other,
}
let mut current_tag = Tag::Other;
let mut current_release: Option<Release> = None;
let regex =
Regex::new(r"(?i)(?P<prefix>.*/)*(?P<name>.+)-[v]{0,1}(?P<version>\d+\.\d+\.\d+)-.+")
.map_err(|err| {
Error::Release(format!(
"Failed constructing regex to parse S3 filenames: {}",
err
))
})?;
// inspecting each XML element we populate our releases list
let mut buf = Vec::new();
let mut releases: Vec<Release> = vec![];
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) => match e.name().into_inner() {
b"Contents" => {
current_tag = Tag::Contents;
if let Some(release) = current_release {
add_to_releases_list(&mut releases, release);
}
current_release = None;
}
b"Key" => current_tag = Tag::Key,
b"LastModified" => current_tag = Tag::LastModified,
_ => current_tag = Tag::Other,
},
Ok(Event::Text(e)) => {
// if we cannot decode a tag text we just ignore it
if let Ok(txt) = e.decode().map(|r| r.into_owned()) {
match current_tag {
Tag::Key => {
let p = PathBuf::from(&txt);
let exe_name = match p.file_name().map(|v| v.to_str()) {
Some(Some(v)) => v,
_ => &txt,
};
if let Some(captures) = regex.captures(&txt) {
let release = current_release.get_or_insert(Release::default());
release.name = captures["name"].to_string();
release.version =
captures["version"].trim_start_matches('v').to_string();
let download_url = format!("{}{}", download_base_url, txt);
#[cfg(feature = "s3-auth")]
let download_url =
auth::s3_signature_v4(&download_url, region, access_key, 300)?;
release.assets = vec![ReleaseAsset {
name: exe_name.to_string(),
download_url,
}];
debug!("Matched release: {:?}", release);
} else {
debug!("Regex mismatch: {:?}", &txt);
}
}
Tag::LastModified => {
let release = current_release.get_or_insert(Release::default());
release.date = txt;
}
_ => (),
}
}
}
Ok(Event::Eof) => {
if let Some(release) = current_release {
add_to_releases_list(&mut releases, release);
}
break; // exits the loop when reaching end of file
}
Err(e) => bail!(
Error::Release,
"Failed when parsing S3 XML response at position {}: {:?}",
reader.buffer_position(),
e
),
_ => (), // There are several other `Event`s we ignore here
}
buf.clear();
}
Ok(releases)
}
// Add a release to the list if it's doesn't exist yet, or merge its asset/s
// details into the release item already existing in the list
fn add_to_releases_list(releases: &mut Vec<Release>, mut rel: Release) {
if !rel.version.is_empty() && !rel.name.is_empty() {
match releases
.iter()
.position(|curr| curr.name == rel.name && curr.version == rel.version)
{
Some(index) => {
rel.assets.append(&mut releases[index].assets);
releases.push(rel);
releases.swap_remove(index);
}
None => releases.push(rel),
}
}
}
#[cfg(test)]
mod tests {
use super::Update;
use crate::update::{Release, ReleaseUpdate};
// ---------------------------------------------------------------------------
// Helpers shared between sync XML-parse tests and async stub tests
// ---------------------------------------------------------------------------
/// Build a minimal `ListBucketResult` XML body with the given `<Key>` entries.
fn list_bucket_xml(keys: &[&str]) -> String {
let contents: String = keys
.iter()
.map(|k| {
format!(
"<Contents><Key>{k}</Key><LastModified>2024-01-01T00:00:00.000Z</LastModified></Contents>"
)
})
.collect();
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Name>my-bucket</Name>{contents}</ListBucketResult>"
)
}
// ---------------------------------------------------------------------------
// parse_s3_response / add_to_releases_list unit tests (no network)
// ---------------------------------------------------------------------------
#[test]
fn parse_s3_response_single_release_single_asset() {
// One <Contents> entry that matches the version regex: name="myapp", version="1.2.3",
// suffix "-x86_64-linux". The trailing Eof flush emits that release.
let xml = list_bucket_xml(&["myapp-1.2.3-x86_64-linux"]);
let releases = super::parse_s3_response(
&xml,
"https://bucket.s3.us-east-1.amazonaws.com/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 1, "one release parsed");
let rel = &releases[0];
assert_eq!(rel.name, "myapp");
assert_eq!(rel.version, "1.2.3");
assert_eq!(rel.assets.len(), 1);
assert_eq!(rel.assets[0].name, "myapp-1.2.3-x86_64-linux");
assert!(
rel.assets[0]
.download_url
.starts_with("https://bucket.s3.us-east-1.amazonaws.com/"),
"download URL uses the supplied base"
);
assert_eq!(rel.date, "2024-01-01T00:00:00.000Z");
}
#[test]
fn parse_s3_response_v_prefix_stripped() {
// A `v`-prefixed version tag (e.g. "myapp-v2.0.0-arm-linux") must have the `v` stripped
// in the parsed release's `version` field, matching the regex's `[v]{0,1}` handling.
let xml = list_bucket_xml(&["myapp-v2.0.0-arm-linux"]);
let releases = super::parse_s3_response(
&xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 1);
assert_eq!(releases[0].version, "2.0.0", "v-prefix must be stripped");
}
#[test]
fn parse_s3_response_multi_asset_merge() {
// Two <Contents> entries for the same name+version represent two assets of one release.
// `add_to_releases_list` must merge them into a single release with two assets.
// The Eof flush handles the last entry, and the interim flush (on the second <Contents>
// start) handles the first.
let xml = list_bucket_xml(&["myapp-3.0.0-x86_64-linux", "myapp-3.0.0-aarch64-linux"]);
let releases = super::parse_s3_response(
&xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 1, "same name+version must be merged");
assert_eq!(
releases[0].assets.len(),
2,
"both assets present after merge"
);
let asset_names: Vec<&str> = releases[0].assets.iter().map(|a| a.name.as_str()).collect();
assert!(
asset_names.contains(&"myapp-3.0.0-x86_64-linux"),
"x86_64 asset present"
);
assert!(
asset_names.contains(&"myapp-3.0.0-aarch64-linux"),
"aarch64 asset present"
);
}
#[test]
fn parse_s3_response_multiple_releases() {
// Multiple distinct name/version combinations produce separate release entries.
// Also exercises the interim <Contents> flush path (not just the Eof flush).
let xml = list_bucket_xml(&[
"myapp-1.0.0-x86_64-linux",
"myapp-2.0.0-x86_64-linux",
"otherapp-1.5.0-x86_64-linux",
]);
let releases = super::parse_s3_response(
&xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 3, "three distinct releases");
let versions: Vec<&str> = releases.iter().map(|r| r.version.as_str()).collect();
assert!(versions.contains(&"1.0.0"));
assert!(versions.contains(&"2.0.0"));
assert!(versions.contains(&"1.5.0"));
}
#[test]
fn parse_s3_response_skips_non_matching_keys() {
// Keys that don't match the version regex (no semver-like version component) must be
// silently ignored; only the matching entry produces a release.
let xml = list_bucket_xml(&[
"README.txt",
"myapp-1.0.0-x86_64-linux",
"some/random/path/no-version",
]);
let releases = super::parse_s3_response(
&xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 1, "only matching key produces a release");
assert_eq!(releases[0].version, "1.0.0");
}
#[test]
fn parse_s3_response_prefix_path_stripped_to_filename() {
// When the <Key> contains a directory prefix (e.g. "releases/myapp-1.0.0-linux"),
// the asset `name` must be just the filename component, not the full path.
let xml = list_bucket_xml(&["releases/myapp-1.0.0-x86_64-linux"]);
let releases = super::parse_s3_response(
&xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert_eq!(releases.len(), 1);
assert_eq!(
releases[0].assets[0].name, "myapp-1.0.0-x86_64-linux",
"asset name is the filename, not the full key path"
);
}
#[test]
fn parse_s3_response_malformed_xml_errors() {
// A body that is not valid XML must surface as an `Err`, not panic.
let bad_xml = "this is not xml at all <<<";
let result = super::parse_s3_response(
bad_xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
);
assert!(result.is_err(), "malformed XML must return Err");
}
#[test]
fn parse_s3_response_empty_body_returns_empty_vec() {
// An empty/minimal XML document with no <Contents> produces an empty releases list (not
// an error), since there is simply nothing to parse.
let xml = "<?xml version=\"1.0\"?><ListBucketResult></ListBucketResult>";
let releases = super::parse_s3_response(
xml,
"https://bucket/",
#[cfg(feature = "s3-auth")]
&None,
#[cfg(feature = "s3-auth")]
&None,
)
.unwrap();
assert!(releases.is_empty(), "empty bucket produces empty list");
}
#[test]
fn add_to_releases_list_skips_entries_with_empty_name_or_version() {
// `add_to_releases_list` must silently drop a release whose name or version is empty,
// matching the `if !rel.version.is_empty() && !rel.name.is_empty()` guard.
let mut releases = Vec::new();
let empty_name = Release::builder()
.name("")
.version("1.0.0")
.build()
.unwrap();
let empty_ver = Release::builder()
.name("myapp")
.version("")
.build()
.unwrap();
super::add_to_releases_list(&mut releases, empty_name);
super::add_to_releases_list(&mut releases, empty_ver);
assert!(
releases.is_empty(),
"entries with empty name or version must be dropped"
);
}
// ---------------------------------------------------------------------------
// Async-fetch tests via a loopback TCP stub
// ---------------------------------------------------------------------------
use std::io::{Read as _, Write as _};
use std::net::TcpListener;
/// Serve a single XML response over a loopback TCP listener, one connection per `Resp`.
/// Returns the base URL (`http://127.0.0.1:<port>/`).
struct Resp {
status: &'static str,
body: String,
}
fn stub(responses: Vec<Resp>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/", listener.local_addr().unwrap());
std::thread::spawn(move || {
for r in responses {
let (mut stream, _) = match listener.accept() {
Ok(c) => c,
Err(_) => return,
};
let mut buf = [0u8; 4096];
let _ = stream.read(&mut buf);
let out = format!(
"HTTP/1.1 {}\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
r.status,
r.body.len(),
r.body
);
let _ = stream.write_all(out.as_bytes());
let _ = stream.flush();
}
});
base
}
/// Build a `fetch_releases_from_s3_async`-ready `Update` whose `EndPoint::Generic` points at
/// the stub base URL. The Generic endpoint does not require a region.
#[cfg(feature = "async")]
fn s3_update(base_url: &str, current_version: &str) -> Update {
Update::configure()
.end_point(super::EndPoint::Generic {
end_point: base_url.to_owned(),
})
.bucket_name("test-bucket")
.bin_name("myapp")
.current_version(current_version)
.build_async()
.unwrap()
}
/// Sync sibling of [`s3_update`]: a `Box<dyn ReleaseUpdate>` pointed at the loopback stub via a
/// `Generic` endpoint (no region required).
fn s3_update_sync(base_url: &str, current_version: &str) -> Box<dyn ReleaseUpdate> {
Update::configure()
.end_point(super::EndPoint::Generic {
end_point: base_url.to_owned(),
})
.bucket_name("test-bucket")
.bin_name("myapp")
.current_version(current_version)
.build()
.unwrap()
}
// --- Sync `Releases`-returning fetch coverage (gap #1) ------------------------------------
//
// The s3 stub harness is otherwise only exercised by the async tests above. These pin the
// *sync* `ReleaseUpdate` fetch methods on the same loopback stub: the one-element
// `get_latest_release` wrap, the strictly-newer-filtered `get_latest_releases` list, the
// current_version carry, and `is_update_available()` agreement between the two paths.
#[test]
fn get_latest_release_sync_wraps_newest_and_carries_current_version() {
// `get_latest_release` (sync) picks the highest version from the bucket listing and wraps
// it in a one-element `Releases` carrying the configured current version, so the pre-check
// works off the single newest release.
let xml = list_bucket_xml(&[
"myapp-0.9.0-x86_64-linux",
"myapp-2.1.0-x86_64-linux",
"myapp-1.0.0-x86_64-linux",
]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update_sync(&base, "1.0.0");
let releases = upd.get_latest_release().unwrap();
assert_eq!(
releases.all().len(),
1,
"get_latest_release yields a one-element Releases"
);
assert_eq!(releases.latest().unwrap().version, "2.1.0");
assert!(
releases.is_update_available().unwrap(),
"2.1.0 > 1.0.0 via the one-element Releases pre-check"
);
}
#[test]
fn get_latest_releases_sync_filters_to_newer_and_prechecks() {
// `get_latest_releases` (sync) returns a `Releases` of strictly-newer releases (newest
// first); `.is_update_available()` / `.latest()` work off it without a second fetch.
let xml = list_bucket_xml(&[
"myapp-0.9.0-x86_64-linux",
"myapp-1.0.0-x86_64-linux",
"myapp-1.5.0-x86_64-linux",
"myapp-2.0.0-x86_64-linux",
]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update_sync(&base, "1.0.0");
let releases = upd.get_latest_releases().unwrap();
let versions: Vec<&str> = releases.all().iter().map(|r| r.version.as_str()).collect();
assert_eq!(
versions,
vec!["2.0.0", "1.5.0"],
"only releases strictly newer than current, newest-first"
);
assert_eq!(releases.latest().unwrap().version, "2.0.0");
assert!(releases.is_update_available().unwrap());
}
#[test]
fn sync_is_update_available_agrees_between_paths_when_up_to_date() {
// gap #1/#4 (sync, s3): when the bucket's newest release equals the current version, the
// one-element `get_latest_release` path (which keeps the newest even if equal) and the
// strictly-newer-filtered `get_latest_releases` path must BOTH report not-available.
let xml = || {
list_bucket_xml(&[
"myapp-2.0.0-x86_64-linux",
"myapp-1.0.0-x86_64-linux",
"myapp-0.9.0-x86_64-linux",
])
};
let base = stub(vec![Resp {
status: "200 OK",
body: xml(),
}]);
let upd = s3_update_sync(&base, "2.0.0");
let single = upd.get_latest_release().unwrap();
assert_eq!(single.latest().unwrap().version, "2.0.0");
assert!(
!single.is_update_available().unwrap(),
"get_latest_release: newest (2.0.0) == current => not available"
);
let base = stub(vec![Resp {
status: "200 OK",
body: xml(),
}]);
let upd = s3_update_sync(&base, "2.0.0");
let list = upd.get_latest_releases().unwrap();
assert!(
list.all().is_empty(),
"nothing strictly newer than 2.0.0 => empty list"
);
assert!(
!list.is_update_available().unwrap(),
"get_latest_releases agrees: not available"
);
}
/// Assert an s3 fetch result is the EXACT structured status error expected for `expected_status`,
/// not merely "one of the three status variants". The load-bearing contract is that a non-2xx
/// listing response is an `Err` carrying the precise status mapping (404 -> `NotFound`,
/// 401/403 -> `Unauthorized`, else -> `HttpStatus`) and that `http_status()` recovers the code.
/// Both reqwest and ureq must produce the identical variant for the same status, so this is
/// client-agnostic and pins cross-client agreement.
fn assert_status_err(
res: crate::errors::Result<crate::update::Releases>,
expected_status: u16,
) {
use crate::errors::Error;
let err = match res {
Err(e) => e,
Ok(_) => panic!(
"a non-2xx ({}) listing response must surface as Err, got Ok",
expected_status
),
};
assert_eq!(
err.http_status(),
Some(expected_status),
"http_status() must recover the injected status {}, got {:?}",
expected_status,
err
);
match expected_status {
404 => assert!(
matches!(err, Error::NotFound { .. }),
"status 404 must surface as Error::NotFound, got {:?}",
err
),
401 | 403 => assert!(
matches!(err, Error::Unauthorized { status, .. } if status == expected_status),
"status {} must surface as Error::Unauthorized, got {:?}",
expected_status,
err
),
_ => assert!(
matches!(err, Error::HttpStatus { status, .. } if status == expected_status),
"status {} must surface as Error::HttpStatus, got {:?}",
expected_status,
err
),
}
}
/// Serve `status` (with an HTTP error body) over a fresh loopback stub and return the sync
/// fetch result for `get_latest_release`. A fresh stub is required per call because the
/// loopback server serves one response per connection.
fn fetch_with_status(status: &'static str) -> crate::errors::Result<crate::update::Releases> {
let base = stub(vec![Resp {
status,
body: "<Error><Code>NoSuchBucket</Code></Error>".to_string(),
}]);
let upd = s3_update_sync(&base, "0.1.0");
upd.get_latest_release()
}
#[test]
fn fetch_404_surfaces_not_found() {
// The s3 fetch path dropped its own `status()` check and now relies on
// `http_client::get`/`send` bailing on a non-2xx status. A 404 must surface as the exact
// `Error::NotFound` variant (not merely "some error", and never an `Ok` parsed from the
// error body), on the sync lane of whichever http client is built in.
assert_status_err(fetch_with_status("404 Not Found"), 404);
// `get_latest_releases` shares the same fetch path; a fresh stub is required because the
// loopback server serves one response per connection.
let base = stub(vec![Resp {
status: "404 Not Found",
body: "<Error><Code>NoSuchBucket</Code></Error>".to_string(),
}]);
let upd = s3_update_sync(&base, "0.1.0");
assert_status_err(upd.get_latest_releases(), 404);
}
#[test]
fn fetch_401_and_403_surface_unauthorized() {
// 401 and 403 both map to the `Unauthorized` variant, carrying their exact code.
assert_status_err(fetch_with_status("401 Unauthorized"), 401);
assert_status_err(fetch_with_status("403 Forbidden"), 403);
}
#[test]
fn fetch_500_and_503_surface_http_status() {
// A server-error status that is not 404/401/403 maps to `HttpStatus` with its exact code.
assert_status_err(fetch_with_status("500 Internal Server Error"), 500);
assert_status_err(fetch_with_status("503 Service Unavailable"), 503);
}
#[test]
fn fetch_400_surfaces_http_status() {
// Boundary: a 4xx that is not 404/401/403 (here 400) maps to `HttpStatus`, not
// `Unauthorized`/`NotFound`.
assert_status_err(fetch_with_status("400 Bad Request"), 400);
}
#[test]
fn get_release_version_sync_finds_exact_version() {
// `get_release_version` (sync) returns only the release matching the requested version, and
// errors when none matches.
let xml = list_bucket_xml(&["myapp-1.0.0-x86_64-linux", "myapp-2.0.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update_sync(&base, "0.1.0");
let rel = upd.get_release_version("1.0.0").unwrap();
assert_eq!(rel.version, "1.0.0");
let xml = list_bucket_xml(&["myapp-1.0.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update_sync(&base, "0.1.0");
assert!(
matches!(
upd.get_release_version("9.9.9"),
Err(crate::errors::Error::Release(_))
),
"missing version must surface as Error::Release"
);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn fetch_releases_from_s3_async_parses_xml_response() {
// Drive `fetch_releases_from_s3_async` against a loopback stub that returns a valid S3
// `ListBucketResult` XML body, and assert the parsed releases.
let xml = list_bucket_xml(&["myapp-2.1.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "0.1.0");
let releases = upd.get_latest_release_async().await.unwrap();
let rel = releases.latest().expect("one-element Releases");
assert_eq!(rel.version, "2.1.0");
assert_eq!(rel.name, "myapp");
}
#[cfg(feature = "async")]
#[tokio::test]
async fn get_latest_releases_async_filters_to_newer_only() {
// A ListBucketResult with releases at versions 0.9.0, 1.0.0, 1.5.0, and 2.0.0.
// With current_version=1.0.0, only 1.5.0 and 2.0.0 should survive (newest-first).
let xml = list_bucket_xml(&[
"myapp-0.9.0-x86_64-linux",
"myapp-1.0.0-x86_64-linux",
"myapp-1.5.0-x86_64-linux",
"myapp-2.0.0-x86_64-linux",
]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "1.0.0");
let releases = upd.get_latest_releases_async().await.unwrap();
let versions: Vec<&str> = releases.all().iter().map(|r| r.version.as_str()).collect();
assert_eq!(
versions,
vec!["2.0.0", "1.5.0"],
"only releases strictly newer than current, newest-first"
);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn get_release_version_async_finds_exact_version() {
// A ListBucketResult with two releases; `get_release_version_async` must return only the
// one matching the requested version.
let xml = list_bucket_xml(&["myapp-1.0.0-x86_64-linux", "myapp-2.0.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "0.1.0");
let rel = upd.get_release_version_async("1.0.0").await.unwrap();
assert_eq!(rel.version, "1.0.0");
}
#[cfg(feature = "async")]
#[tokio::test]
async fn get_release_version_async_errors_on_missing_version() {
// When the requested version does not exist in the bucket listing, the call must error
// with `Error::Release`.
let xml = list_bucket_xml(&["myapp-1.0.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "0.1.0");
let res = upd.get_release_version_async("9.9.9").await;
assert!(
matches!(res, Err(crate::errors::Error::Release(_))),
"missing version must surface as Error::Release"
);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn is_update_available_async_true_then_false() {
// D2 (async): the pre-check is `get_latest_release_async().await?.is_update_available()`.
// The bucket's newest release is 2.0.0, so an update is available from 1.0.0 but not from
// 2.0.0. A fresh stub is needed per call because the loopback server serves one response
// per connection.
let xml = list_bucket_xml(&["myapp-1.0.0-x86_64-linux", "myapp-2.0.0-x86_64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml.clone(),
}]);
let upd = s3_update(&base, "1.0.0");
assert!(
upd.get_latest_release_async()
.await
.unwrap()
.is_update_available()
.unwrap(),
"2.0.0 > 1.0.0 => update available"
);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "2.0.0");
assert!(
!upd.get_latest_release_async()
.await
.unwrap()
.is_update_available()
.unwrap(),
"2.0.0 not newer than 2.0.0 => no update"
);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn get_latest_release_async_multi_asset_merge() {
// Two <Contents> entries for the same name+version are merged into a single release with
// two assets. `get_latest_release_async` must return that merged release.
let xml = list_bucket_xml(&["myapp-3.0.0-x86_64-linux", "myapp-3.0.0-aarch64-linux"]);
let base = stub(vec![Resp {
status: "200 OK",
body: xml,
}]);
let upd = s3_update(&base, "0.1.0");
let releases = upd.get_latest_release_async().await.unwrap();
let rel = releases.latest().expect("one-element Releases");
assert_eq!(rel.version, "3.0.0");
assert_eq!(
rel.assets.len(),
2,
"both assets present after async multi-asset merge"
);
}
fn rel(version: &str) -> Release {
Release::builder().version(version).build().unwrap()
}
#[test]
fn pick_latest_returns_highest_version() {
let releases = [rel("1.0.0"), rel("2.3.1"), rel("2.0.0"), rel("1.9.9")];
assert_eq!(super::pick_latest(&releases).unwrap().version, "2.3.1");
}
#[test]
fn pick_latest_errors_on_empty() {
assert!(super::pick_latest(&[]).is_err());
}
#[test]
fn pick_latest_ignores_unparseable_versions() {
// `pick_latest` does NOT pre-filter, so its comparator's `Err(_)` branch (unparseable
// version string) is reachable here. A release with a non-semver version must be ignored
// and the highest parseable version still chosen. (`choose_latest_release`/`sort_newer`
// pre-filter unparseable versions, so their comparator `Err(_)` arm is unreachable.)
let releases = [rel("1.0.0"), rel("not-a-version"), rel("2.1.0")];
assert_eq!(super::pick_latest(&releases).unwrap().version, "2.1.0");
// Even when the unparseable one is first/last, it never wins.
let releases = [rel("bogus"), rel("1.5.0")];
assert_eq!(super::pick_latest(&releases).unwrap().version, "1.5.0");
}
#[test]
fn sort_newer_ignores_unparseable_versions() {
// The pre-filter drops the unparseable version before the sort; only parseable, strictly
// newer versions survive, newest-first.
let releases = vec![rel("garbage"), rel("2.0.0"), rel("1.5.0"), rel("1.0.0")];
let newer = super::sort_newer(releases, "1.0.0");
let versions: Vec<_> = newer.iter().map(|r| r.version.as_str()).collect();
assert_eq!(versions, vec!["2.0.0", "1.5.0"]);
}
#[cfg(feature = "s3-auth")]
#[test]
fn access_key_is_reexported_and_built_from_tuples() {
// `AccessKey` is re-exported at the backend module level and is built via the tuple `From`
// impls (it is `#[non_exhaustive]`, so no struct literal from outside this module).
let from_strs: super::AccessKey = ("AKIA-id", "secret").into();
assert_eq!(from_strs.access_key_id, "AKIA-id");
assert_eq!(from_strs.secret_access_key, "secret");
let from_owned: super::AccessKey = (String::from("id2"), String::from("secret2")).into();
assert_eq!(from_owned.access_key_id, "id2");
assert_eq!(from_owned.secret_access_key, "secret2");
}
#[cfg(feature = "s3-auth")]
#[test]
fn access_key_setter_accepts_tuple_and_reexported_type() {
// The `access_key` setter takes `impl Into<AccessKey>`, so both a bare tuple and an
// already-built `AccessKey` (named via the re-export) compile and build.
let _ = Update::configure()
.bucket_name("bucket")
.region("us-east-1")
.bin_name("my_bin")
.current_version("0.1.0")
.access_key(("id", "secret"))
.build()
.unwrap();
let key: super::AccessKey = ("id", "secret").into();
let _ = Update::configure()
.bucket_name("bucket")
.region("us-east-1")
.bin_name("my_bin")
.current_version("0.1.0")
.access_key(key)
.build()
.unwrap();
}
#[test]
fn filter_target_setter_exists_on_release_list_builder() {
// The renamed `filter_target` setter must exist on the s3 `ReleaseListBuilder` and the
// builder must build with the required fields present.
let _list = super::ReleaseList::configure()
.bucket_name("bucket")
.region("us-east-1")
.filter_target("x86_64-unknown-linux-gnu")
.build()
.unwrap();
}
#[test]
fn release_list_build_surfaces_invalid_header() {
// A bad header on the `ReleaseListBuilder` must fail at `build()` via `request.check()`
// with `Error::Config`, not panic.
let res = super::ReleaseList::configure()
.bucket_name("bucket")
.request_header("inva lid", "ok")
.build();
assert!(
matches!(res, Err(crate::errors::Error::Config(_))),
"invalid header must surface as Error::Config from ReleaseList build()"
);
}
#[test]
fn sort_newer_keeps_only_newer_descending() {
let releases = vec![rel("0.9.0"), rel("1.5.0"), rel("1.0.0"), rel("2.0.0")];
let newer = super::sort_newer(releases, "1.0.0");
// 0.9.0 and 1.0.0 are not strictly newer than 1.0.0; the rest are, newest-first.
let versions: Vec<_> = newer.iter().map(|r| r.version.as_str()).collect();
assert_eq!(versions, vec!["2.0.0", "1.5.0"]);
}
#[test]
fn find_version_matches_exact() {
let releases = [rel("1.0.0"), rel("1.2.3"), rel("2.0.0")];
assert_eq!(
super::find_version(&releases, "1.2.3").unwrap().version,
"1.2.3"
);
assert!(super::find_version(&releases, "9.9.9").is_err());
}
fn configured() -> Box<dyn ReleaseUpdate> {
Update::configure()
.bucket_name("bucket")
.asset_prefix("prefix")
.region("us-east-1")
.bin_name("my_bin")
.target("x86_64-unknown-linux-gnu")
.asset_identifier("musl")
.current_version("0.1.0")
.build()
.unwrap()
}
#[test]
fn identifier_and_str_accessors_are_wired() {
let upd = configured();
// `identifier` is newly supported on the s3 builder.
assert_eq!(upd.asset_identifier(), Some("musl"));
assert_eq!(upd.target(), "x86_64-unknown-linux-gnu");
assert_eq!(upd.current_version(), "0.1.0");
}
#[test]
fn default_api_headers_rejects_invalid_token_without_panicking() {
let upd = configured();
// A token containing a newline is not a valid HTTP header value. The default
// `api_headers` impl must surface an error rather than panic (it previously
// `unwrap()`ed the parse).
assert!(upd.api_headers(Some("bad\ntoken")).is_err());
// A well-formed token still succeeds.
assert!(upd.api_headers(Some("good-token")).is_ok());
}
// ---------------------------------------------------------------------------
// build_s3_api_url: endpoint/region/prefix URL construction (pure, no network)
// ---------------------------------------------------------------------------
/// Call `build_s3_api_url`, threading the `s3-auth`-only `access_key` argument behind the
/// feature gate so the same call site compiles with and without `s3-auth`. With no access key
/// the returned `api_url` is unsigned, so the tests below can assert on the raw URL shape.
fn api_url(
end_point: super::EndPoint,
bucket: &str,
region: Option<&str>,
prefix: Option<&str>,
) -> crate::errors::Result<(String, String)> {
super::build_s3_api_url(
&end_point,
bucket,
®ion.map(str::to_owned),
&prefix.map(str::to_owned),
#[cfg(feature = "s3-auth")]
&None,
)
}
#[test]
fn build_s3_api_url_s3_endpoint_shape() {
// EndPoint::S3 forms `https://<bucket>.s3.<region>.amazonaws.com/` as the download base,
// and the listing url appends the v2 `list-type=2&max-keys=...` query.
let (base, url) =
api_url(super::EndPoint::S3, "my-bucket", Some("eu-west-1"), None).unwrap();
assert_eq!(base, "https://my-bucket.s3.eu-west-1.amazonaws.com/");
assert_eq!(
url,
"https://my-bucket.s3.eu-west-1.amazonaws.com/?list-type=2&max-keys=100"
);
}
#[test]
fn build_s3_api_url_dualstack_endpoint_shape() {
// EndPoint::S3DualStack injects the `dualstack` infix into the host.
let (base, url) =
api_url(super::EndPoint::S3DualStack, "b", Some("us-east-2"), None).unwrap();
assert_eq!(base, "https://b.s3.dualstack.us-east-2.amazonaws.com/");
assert!(url.starts_with("https://b.s3.dualstack.us-east-2.amazonaws.com/?list-type=2"));
}
#[test]
fn build_s3_api_url_digitalocean_endpoint_shape() {
// EndPoint::DigitalOceanSpaces uses `<bucket>.<region>.digitaloceanspaces.com`.
let (base, url) = api_url(
super::EndPoint::DigitalOceanSpaces,
"space",
Some("nyc3"),
None,
)
.unwrap();
assert_eq!(base, "https://space.nyc3.digitaloceanspaces.com/");
assert!(url.starts_with("https://space.nyc3.digitaloceanspaces.com/?list-type=2"));
}
#[test]
fn build_s3_api_url_gcs_ignores_region_and_uses_maxkeys_only() {
// EndPoint::GCS targets `storage.googleapis.com/<bucket>/`, does NOT embed a region, and
// its listing query is `max-keys` only (no `list-type=2`, which is S3-specific).
let (base, url) = api_url(super::EndPoint::GCS, "gbucket", None, None).unwrap();
assert_eq!(base, "https://storage.googleapis.com/gbucket/");
assert_eq!(url, "https://storage.googleapis.com/gbucket/?max-keys=100");
assert!(
!url.contains("list-type=2"),
"GCS listing must not use the S3-only list-type=2 param"
);
}
#[test]
fn build_s3_api_url_generic_passes_endpoint_through() {
// EndPoint::Generic uses the supplied URL verbatim as the download base (region is not
// consumed) and appends the v2 `list-type=2` listing query.
let (base, url) = api_url(
super::EndPoint::Generic {
end_point: "https://s3.example.com/bucket/".to_owned(),
},
"ignored-bucket",
None,
None,
)
.unwrap();
assert_eq!(base, "https://s3.example.com/bucket/");
assert_eq!(
url,
"https://s3.example.com/bucket/?list-type=2&max-keys=100"
);
}
#[test]
fn build_s3_api_url_appends_asset_prefix() {
// A configured asset_prefix is appended as `&prefix=<value>` to the listing query; with
// no prefix the segment is absent.
let (_base, with_prefix) = api_url(
super::EndPoint::S3,
"b",
Some("us-east-1"),
Some("releases/"),
)
.unwrap();
assert!(
with_prefix.ends_with("&prefix=releases/"),
"prefix must be appended: {}",
with_prefix
);
let (_base, no_prefix) =
api_url(super::EndPoint::S3, "b", Some("us-east-1"), None).unwrap();
assert!(
!no_prefix.contains("prefix="),
"no prefix segment when asset_prefix is None"
);
}
#[test]
fn build_s3_api_url_missing_region_errors_for_region_endpoints() {
// S3, S3DualStack and DigitalOceanSpaces all interpolate the region into the host, so a
// missing region must surface as `Error::Config` (not a panic or a malformed URL).
for ep in [
super::EndPoint::S3,
super::EndPoint::S3DualStack,
super::EndPoint::DigitalOceanSpaces,
] {
let res = api_url(ep, "b", None, None);
assert!(
matches!(res, Err(crate::errors::Error::Config(_))),
"region-requiring endpoint without region must error with Error::Config"
);
}
}
#[test]
fn build_s3_api_url_generic_and_gcs_succeed_without_region() {
// Generic and GCS never read the region, so both must build successfully when region is
// absent (the region-requiring endpoints are covered by the error test above).
assert!(api_url(super::EndPoint::GCS, "b", None, None).is_ok());
assert!(api_url(
super::EndPoint::Generic {
end_point: "https://s3.example.com/".to_owned()
},
"b",
None,
None
)
.is_ok());
}
// The endpoint/region pairing is now validated at `build()` time (not deferred to the first
// network call), so a region-requiring endpoint without a region fails where every other
// required-field error is reported.
#[test]
fn build_errors_without_region_for_region_endpoints() {
let res = Update::configure()
.end_point(super::EndPoint::S3)
.bucket_name("bucket")
.bin_name("bin")
.current_version("0.1.0")
.build();
assert!(
matches!(res, Err(crate::errors::Error::Config(_))),
"S3 endpoint without region must fail at build() with Error::Config"
);
let list = super::ReleaseList::configure()
.end_point(super::EndPoint::DigitalOceanSpaces)
.bucket_name("bucket")
.build();
assert!(
matches!(list, Err(crate::errors::Error::Config(_))),
"ReleaseList build() must also enforce the region requirement"
);
}
// Async sibling of `build_errors_without_region_for_region_endpoints`: `build_async()` runs the
// same `check_endpoint_region` validation as the sync `build()`, so a region-requiring endpoint
// without a region must fail at `build_async()` (not be deferred to the first network call), and
// a region-free endpoint (GCS/Generic) must build without one.
#[cfg(feature = "async")]
#[test]
fn build_async_errors_without_region_for_region_endpoints() {
let res = Update::configure()
.end_point(super::EndPoint::S3)
.bucket_name("b")
.bin_name("x")
.current_version("0.1.0")
.build_async();
assert!(
matches!(res, Err(crate::errors::Error::Config(_))),
"S3 endpoint without region must fail at build_async() with Error::Config, got {:?}",
res.map(|_| "Ok")
);
}
#[cfg(feature = "async")]
#[test]
fn build_async_succeeds_without_region_for_generic_and_gcs() {
assert!(
Update::configure()
.end_point(super::EndPoint::GCS)
.bucket_name("b")
.bin_name("x")
.current_version("0.1.0")
.build_async()
.is_ok(),
"GCS endpoint needs no region at build_async()"
);
assert!(
Update::configure()
.end_point(super::EndPoint::Generic {
end_point: "https://s3.example.com/".to_owned()
})
.bucket_name("b")
.bin_name("x")
.current_version("0.1.0")
.build_async()
.is_ok(),
"Generic endpoint needs no region at build_async()"
);
}
#[test]
fn build_succeeds_without_region_for_generic_and_gcs() {
assert!(Update::configure()
.end_point(super::EndPoint::GCS)
.bucket_name("bucket")
.bin_name("bin")
.current_version("0.1.0")
.build()
.is_ok());
assert!(Update::configure()
.end_point(super::EndPoint::Generic {
end_point: "https://s3.example.com/".to_owned()
})
.bucket_name("bucket")
.bin_name("bin")
.current_version("0.1.0")
.build()
.is_ok());
}
// ---------------------------------------------------------------------------
// s3-auth: SigV4 query-signing structural invariants (deterministic, no real
// signature assertions since the timestamp/HMAC are time-dependent)
// ---------------------------------------------------------------------------
#[cfg(feature = "s3-auth")]
#[test]
fn s3_signature_v4_no_access_key_returns_url_unchanged() {
// With no access key the signer is a no-op: the URL is returned verbatim, so an
// unauthenticated (public-bucket) request carries no SigV4 query params.
let url = "https://b.s3.us-east-1.amazonaws.com/key?list-type=2";
let out = super::auth::s3_signature_v4(url, &Some("us-east-1".into()), &None, 300).unwrap();
assert_eq!(out, url, "missing access key must return the URL unchanged");
}
#[cfg(feature = "s3-auth")]
#[test]
fn s3_signature_v4_signed_url_has_required_query_params() {
// With an access key the signer appends the AWS SigV4 presigned-query params. We cannot
// assert the exact signature (it depends on the current wall-clock timestamp and HMAC),
// but the structural invariants are deterministic.
let url = "https://b.s3.us-east-1.amazonaws.com/path/to/key";
let key: super::AccessKey = ("AKIAEXAMPLE", "secretkey").into();
let out =
super::auth::s3_signature_v4(url, &Some("us-east-1".into()), &Some(key), 300).unwrap();
assert!(out.contains("X-Amz-Algorithm=AWS4-HMAC-SHA256"));
assert!(out.contains("X-Amz-Credential="));
assert!(out.contains("X-Amz-Date="));
assert!(out.contains("X-Amz-Expires=300"));
assert!(out.contains("X-Amz-SignedHeaders=host"));
assert!(out.contains("X-Amz-Signature="));
// The signature is the final param and is a lowercase hex SHA-256 HMAC (64 hex chars).
let sig = out
.rsplit("X-Amz-Signature=")
.next()
.expect("signature param present");
assert_eq!(sig.len(), 64, "SigV4 signature is 32 bytes hex-encoded");
assert!(
sig.bytes().all(|b| b.is_ascii_hexdigit()),
"signature must be lowercase hex"
);
// The credential scope embeds the region and the s3/aws4_request terminator. The whole
// X-Amz-Credential value is URI-encoded in the query string, so the scope separators are
// percent-encoded slashes (`%2F`).
assert!(
out.contains("%2Fus-east-1%2Fs3%2Faws4_request"),
"credential scope must embed region and service scope: {}",
out
);
// The base path is preserved ahead of the query string.
assert!(out.starts_with("https://b.s3.us-east-1.amazonaws.com/path/to/key?"));
}
#[cfg(feature = "s3-auth")]
#[test]
fn s3_signature_v4_defaults_region_to_us_east_1() {
// When region is None the signer falls back to `us-east-1` in the credential scope.
let key: super::AccessKey = ("AKIA", "secret").into();
let out =
super::auth::s3_signature_v4("https://b.s3.amazonaws.com/k", &None, &Some(key), 300)
.unwrap();
assert!(
out.contains("%2Fus-east-1%2Fs3%2Faws4_request"),
"absent region must default to us-east-1: {}",
out
);
}
#[cfg(feature = "s3-auth")]
#[test]
fn build_s3_api_url_signs_listing_url_when_access_key_present() {
// The listing url returned by `build_s3_api_url` is signed when an access key is supplied,
// and left unsigned otherwise. This exercises the s3-auth branch at the call site (not
// just the bare signer), preserving the existing `list-type=2` query under signing.
let key: super::AccessKey = ("AKIA", "secret").into();
let region = Some("us-east-1".to_owned());
let (_base, signed) =
super::build_s3_api_url(&super::EndPoint::S3, "b", ®ion, &None, &Some(key)).unwrap();
assert!(signed.contains("X-Amz-Signature="));
assert!(signed.contains("X-Amz-Credential="));
assert!(
signed.contains("list-type=2"),
"the original listing query must survive signing"
);
let (_base, unsigned) =
super::build_s3_api_url(&super::EndPoint::S3, "b", ®ion, &None, &None).unwrap();
assert!(
!unsigned.contains("X-Amz-Signature="),
"no access key => unsigned listing url"
);
}
#[cfg(feature = "s3-auth")]
#[test]
fn parse_s3_response_signs_download_urls_when_access_key_present() {
// Under s3-auth, `parse_s3_response` signs each asset's download URL. The unsigned vs
// signed distinction is the load-bearing behavior: with an access key the asset URL gains
// the SigV4 presign params; with none it stays a plain URL.
let xml = list_bucket_xml(&["myapp-1.2.3-x86_64-linux"]);
let region = Some("us-east-1".to_owned());
let key: super::AccessKey = ("AKIA", "secret").into();
let signed = super::parse_s3_response(
&xml,
"https://b.s3.us-east-1.amazonaws.com/",
®ion,
&Some(key),
)
.unwrap();
let signed_url = &signed[0].assets[0].download_url;
assert!(
signed_url.contains("X-Amz-Signature=") && signed_url.contains("X-Amz-Credential="),
"signed asset download url must carry SigV4 params: {}",
signed_url
);
let unsigned = super::parse_s3_response(
&xml,
"https://b.s3.us-east-1.amazonaws.com/",
®ion,
&None,
)
.unwrap();
let unsigned_url = &unsigned[0].assets[0].download_url;
assert!(
!unsigned_url.contains("X-Amz-Signature="),
"no access key => unsigned asset download url: {}",
unsigned_url
);
assert_eq!(
unsigned_url, "https://b.s3.us-east-1.amazonaws.com/myapp-1.2.3-x86_64-linux",
"unsigned download url is the plain base+key"
);
}
#[test]
fn api_headers_uses_the_trait_default_no_override() {
// s3 passes NO `{api_headers}` override to `impl_update_config_accessors!`, so it must get
// the `UpdateConfig` trait default: a single `token` Authorization header and, crucially,
// *no* User-Agent (unlike github/gitlab/gitea which override with one).
let upd = configured();
let headers = upd.api_headers(Some("secret")).unwrap();
assert!(
headers
.get(crate::http_client::header::USER_AGENT)
.is_none(),
"the default api_headers (no override) must not set a User-Agent"
);
assert_eq!(
headers
.get(crate::http_client::header::AUTHORIZATION)
.unwrap()
.to_str()
.unwrap(),
"token secret"
);
}
// --- Item 6: auth_token deprecated shim ------------------------------------------------
#[test]
#[allow(deprecated)]
fn release_list_builder_auth_token_is_a_noop() {
// The deprecated `auth_token` shim must compile, accept a token, and have no visible
// effect: the bucket/key path required for a real build is still the deciding factor.
let result = crate::backends::s3::ReleaseList::configure()
.bucket_name("my-bucket")
.asset_prefix("myapp")
.region("us-east-1")
.auth_token("any-token")
.build();
// Build must succeed regardless of the shim token value.
assert!(result.is_ok(), "auth_token shim must not break the build");
}
#[test]
#[allow(deprecated)]
fn update_builder_auth_token_is_a_noop() {
// Same for the UpdateBuilder shim.
let result = Update::configure()
.bucket_name("my-bucket")
.asset_prefix("myapp")
.region("us-east-1")
.bin_name("myapp")
.current_version("0.1.0")
.auth_token("any-token")
.build();
assert!(result.is_ok(), "auth_token shim must not break the build");
}
}