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
use std::io::{self, ErrorKind, Read};
use std::sync::Arc;
use crate::bundle::{verify_manifest_signature, BundleManifest, ManifestVerification};
use calimero_primitives::application::{
Application, ApplicationBlob, ApplicationId, ApplicationSource,
};
use calimero_primitives::blobs::BlobId;
use calimero_primitives::hash::Hash;
use calimero_store::{key, types};
use camino::{Utf8Path, Utf8PathBuf};
use eyre::bail;
use flate2::read::GzDecoder;
use futures_util::{io::Cursor, TryStreamExt};
use reqwest::Url;
use semver::Version;
use serde_json;
use sha2::{Digest, Sha256};
use std::fs;
use tar::Archive;
use tokio::fs::File;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tracing::{debug, trace, warn};
use super::NodeClient;
impl NodeClient {
pub fn get_application(
&self,
application_id: &ApplicationId,
) -> eyre::Result<Option<Application>> {
let handle = self.datastore.handle();
let key = key::ApplicationMeta::new(*application_id);
let Some(application) = handle.get(&key)? else {
return Ok(None);
};
let application = Application::new(
*application_id,
ApplicationBlob {
bytecode: application.bytecode.blob_id(),
compiled: application.compiled.blob_id(),
},
application.size,
application.source.parse()?,
application.metadata.into_vec(),
);
Ok(Some(application))
}
pub async fn get_application_bytes(
&self,
application_id: &ApplicationId,
) -> eyre::Result<Option<Arc<[u8]>>> {
let handle = self.datastore.handle();
let key = key::ApplicationMeta::new(*application_id);
let Some(application) = handle.get(&key)? else {
return Ok(None);
};
// Determine if this is a bundle by checking package/version
// Bundles have real package/version values, non-bundles use "unknown"/"0.0.0"
// This avoids repeated decompression on every get_application_bytes call
let is_bundle =
application.package.as_ref() != "unknown" && application.version.as_ref() != "0.0.0";
// Get blob bytes
let Some(blob_bytes) = self
.get_blob_bytes(&application.bytecode.blob_id(), None)
.await?
else {
bail!("fatal: application points to dangling blob");
};
if is_bundle {
// This is a bundle, extract WASM from extracted directory or bundle
// Extract manifest and verify signature (blocking I/O wrapped in spawn_blocking)
// Signature verification ensures blob integrity even when re-extracting
let blob_bytes_clone = Arc::clone(&blob_bytes);
let (_, manifest) = tokio::task::spawn_blocking(move || {
Self::verify_and_extract_manifest(&blob_bytes_clone)
})
.await??;
let package = &manifest.package;
let version = &manifest.app_version;
// Resolve relative path against node root (must be done before spawn_blocking)
let blobstore_root = self.blobstore.root_path();
let node_root = blobstore_root
.parent()
.ok_or_else(|| eyre::eyre!("blobstore root has no parent"))?
.to_path_buf();
let extract_dir = node_root
.join("applications")
.join(package)
.join(version)
.join("extracted");
// Get WASM path from manifest (fallback to "app.wasm" for backward compatibility)
let wasm_relative_path = manifest
.wasm
.as_ref()
.map(|w| w.path.as_str())
.unwrap_or("app.wasm");
// Validate WASM path to prevent path traversal attacks
// Check that the relative path doesn't contain ".." components that would escape
if wasm_relative_path.contains("..") {
bail!(
"WASM path traversal detected: {} contains '..' component",
wasm_relative_path
);
}
let wasm_path = extract_dir.join(wasm_relative_path);
// Additional validation: ensure the resolved path stays within extract_dir
// Use canonicalize if path exists, otherwise validate components
if wasm_path.exists() {
let canonical_wasm = wasm_path.canonicalize_utf8()?;
// extract_dir might not exist if wasm_relative_path contains subdirectories
// Reconstruct canonical extract_dir from wasm_path by removing relative path components
let canonical_extract = if extract_dir.exists() {
extract_dir.canonicalize_utf8()?
} else {
// Reconstruct extract_dir from wasm_path by removing wasm_relative_path components
// Since we validated wasm_relative_path doesn't contain "..", this is safe
let wasm_parent = wasm_path
.parent()
.ok_or_else(|| eyre::eyre!("WASM path has no parent directory"))?;
let wasm_parent_canonical = wasm_parent.canonicalize_utf8()?;
// Count depth of wasm_relative_path (number of path components)
let relative_depth = wasm_relative_path
.split('/')
.filter(|s| !s.is_empty())
.count()
.saturating_sub(1); // Subtract 1 for the filename itself
// Go up relative_depth levels from wasm_parent to get extract_dir
let mut canonical_extract_candidate = wasm_parent_canonical.clone();
for _ in 0..relative_depth {
if let Some(parent) = canonical_extract_candidate.parent() {
canonical_extract_candidate = parent.to_path_buf();
} else {
bail!("Cannot reconstruct extract_dir from WASM path");
}
}
canonical_extract_candidate.try_into().map_err(|_| {
eyre::eyre!("Failed to convert extract_dir path to Utf8PathBuf")
})?
};
// Ensure canonical_wasm is within canonical_extract
if !canonical_wasm.starts_with(&canonical_extract) {
bail!(
"WASM path traversal detected: {} escapes extraction directory {}",
wasm_relative_path,
extract_dir
);
}
}
if wasm_path.exists() {
let wasm_bytes = tokio::fs::read(&wasm_path).await?;
return Ok(Some(wasm_bytes.into()));
} else {
// Fallback: re-extract from bundle blob if extracted files missing
warn!(
wasm_path = %wasm_path,
"extracted WASM not found, attempting to re-extract from bundle and persist to disk"
);
// Remove marker file if it exists (files were deleted, marker is stale)
let marker_file_path = extract_dir.join(".extracted");
if marker_file_path.exists() {
let _ = tokio::fs::remove_file(&marker_file_path).await;
}
// Re-extract entire bundle to disk (not just WASM) so future calls don't need to re-extract
// This handles the case where sync_context_config installed the app before blob arrived
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let blob_bytes_clone = Arc::clone(&blob_bytes);
let manifest_clone = manifest.clone();
let extract_dir_clone = extract_dir.to_path_buf();
let node_root_clone = node_root.to_path_buf();
let package_clone = package.to_string();
let version_clone = version.to_string();
tokio::task::spawn_blocking(move || {
Self::extract_bundle_artifacts(
&blob_bytes_clone,
&manifest_clone,
&extract_dir_clone,
&node_root_clone,
&package_clone,
&version_clone,
)
})
.await??;
// Now read the WASM file that was just extracted
if wasm_path.exists() {
let wasm_bytes = tokio::fs::read(&wasm_path).await?;
return Ok(Some(wasm_bytes.into()));
}
bail!("WASM file not found in bundle after extraction");
}
}
// Single WASM installation (existing behavior)
// Reuse blob_bytes that were already fetched for bundle detection
Ok(Some(blob_bytes))
}
pub fn has_application(&self, application_id: &ApplicationId) -> eyre::Result<bool> {
let handle = self.datastore.handle();
let key = key::ApplicationMeta::new(*application_id);
if let Some(application) = handle.get(&key)? {
return self.has_blob(&application.bytecode.blob_id());
}
Ok(false)
}
pub fn install_application(
&self,
blob_id: &BlobId,
size: u64,
source: &ApplicationSource,
metadata: Vec<u8>,
package: &str,
version: &str,
signer_id: Option<&str>,
is_bundle: bool,
) -> eyre::Result<ApplicationId> {
// For bundles: signer_id is required
// For non-bundles: signer_id is optional (backwards compatibility)
// Note: Empty string is used as a sentinel value for non-bundle applications.
// This distinguishes 'no signer' (non-bundle) from 'has signer' (bundle) cases.
// Non-bundle installations cannot be upgraded to signed bundle installations
// without re-installation.
let signer_id_str = signer_id.unwrap_or("");
let application = types::ApplicationMeta::new(
key::BlobMeta::new(*blob_id),
size,
source.to_string().into_boxed_str(),
metadata.into_boxed_slice(),
key::BlobMeta::new(BlobId::from([0; 32])),
package.to_owned().into_boxed_str(),
version.to_owned().into_boxed_str(),
signer_id_str.to_owned().into_boxed_str(),
);
let application_id = if is_bundle {
// For bundles: use package and signer_id for deterministic ApplicationId
// This creates a stable application identity based on who signed the bundle,
// allowing version upgrades while maintaining the same ApplicationId
let components = (&application.package, &application.signer_id);
ApplicationId::from(*Hash::hash_borsh(&components)?)
} else {
// For single WASM: use current logic (blob_id, size, source, metadata)
// Maintains backward compatibility for non-bundle installations
let components = (
application.bytecode,
application.size,
&application.source,
&application.metadata,
);
ApplicationId::from(*Hash::hash_borsh(&components)?)
};
let mut handle = self.datastore.handle();
let key = key::ApplicationMeta::new(application_id);
handle.put(&key, &application)?;
Ok(application_id)
}
/// Check if a path points to a bundle archive (.mpk - Mero Package Kit)
fn is_bundle_archive(path: &Utf8Path) -> bool {
path.extension().map(|ext| ext == "mpk").unwrap_or(false)
}
pub async fn install_application_from_path(
&self,
path: Utf8PathBuf,
metadata: Vec<u8>,
package: Option<String>,
version: Option<String>,
) -> eyre::Result<ApplicationId> {
let metadata_len = metadata.len();
debug!(
path = %path,
metadata_len,
"install_application_from_path started"
);
let path = match path.canonicalize_utf8() {
Ok(canonicalized) => canonicalized,
Err(err) if err.kind() == ErrorKind::NotFound => {
bail!("application file not found at {}", path);
}
Err(err) => return Err(err.into()),
};
trace!(path = %path, "application path canonicalized");
// Detect bundle vs single WASM
if Self::is_bundle_archive(&path) {
return self.install_bundle_from_path(path, metadata).await;
}
// For non-bundle installations, use provided package/version or defaults
let package = package.as_deref().unwrap_or("unknown");
let version = version.as_deref().unwrap_or("0.0.0");
// Existing single WASM installation path
let file = match File::open(&path).await {
Ok(file) => file,
Err(err) if err.kind() == ErrorKind::NotFound => {
bail!("application file not found at {}", path);
}
Err(err) => return Err(err.into()),
};
trace!(path = %path, "application file opened");
let expected_size = file.metadata().await?.len();
debug!(
path = %path,
expected_size,
"install_application_from_path discovered file size"
);
let (blob_id, size) = self
.add_blob(file.compat(), Some(expected_size), None)
.await?;
debug!(
%blob_id,
expected_size,
stored_size = size,
"application blob added via add_blob"
);
let Ok(uri) = Url::from_file_path(path) else {
bail!("non-absolute path")
};
self.install_application(
&blob_id,
size,
&uri.as_str().parse()?,
metadata,
package,
version,
None, // signer_id: None for non-bundle installations
false, // is_bundle: false for single WASM
)
}
pub async fn install_application_from_url(
&self,
url: Url,
metadata: Vec<u8>,
expected_hash: Option<&Hash>,
) -> eyre::Result<ApplicationId> {
let uri = url.as_str().parse()?;
let response = reqwest::Client::new().get(url.clone()).send().await?;
let expected_size = response.content_length();
// Check if URL indicates a bundle archive (.mpk - Mero Package Kit)
let is_bundle = url.path().ends_with(".mpk");
if is_bundle {
// Download entire bundle into memory
let bundle_data = Arc::new(response.bytes().await?.to_vec());
// Store entire bundle as a single blob
let cursor = Cursor::new(bundle_data.as_slice());
let (bundle_blob_id, stored_size) = self
.add_blob(cursor, Some(bundle_data.len() as u64), expected_hash)
.await?;
debug!(
%bundle_blob_id,
bundle_size = bundle_data.len(),
stored_size,
"bundle downloaded and stored as blob"
);
// Extract bundle manifest and verify signature
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_data_clone = Arc::clone(&bundle_data);
let (verification, manifest) = tokio::task::spawn_blocking(move || {
Self::verify_and_extract_manifest(&bundle_data_clone)
})
.await??;
let signer_id = verification.signer_id;
// Extract package and version from manifest
let package = &manifest.package;
let version = &manifest.app_version;
// Extract artifacts with deduplication
// Use node root (parent of blobstore) instead of blobstore root
// Must be done before spawn_blocking
let blobstore_root = self.blobstore.root_path();
let node_root = blobstore_root
.parent()
.ok_or_else(|| eyre::eyre!("blobstore root has no parent"))?
.to_path_buf();
// Extract directory is derived from package and version
let extract_dir = node_root
.join("applications")
.join(package)
.join(version)
.join("extracted");
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_data_clone = Arc::clone(&bundle_data);
let manifest_clone = manifest.clone();
let extract_dir_clone = extract_dir.clone();
let node_root_clone = node_root.clone();
let package_clone = package.to_string();
let version_clone = version.to_string();
tokio::task::spawn_blocking(move || {
Self::extract_bundle_artifacts(
&bundle_data_clone,
&manifest_clone,
&extract_dir_clone,
&node_root_clone,
&package_clone,
&version_clone,
)
})
.await??;
// Extract metadata from bundle manifest and serialize it
// Bundle manifest contains metadata (name, description, author, links, etc.)
let bundle_metadata = {
let mut metadata_obj = serde_json::Map::new();
metadata_obj.insert(
"package".to_string(),
serde_json::Value::String(package.clone()),
);
metadata_obj.insert(
"version".to_string(),
serde_json::Value::String(version.clone()),
);
if let Some(ref metadata) = manifest.metadata {
metadata_obj.insert(
"name".to_string(),
serde_json::Value::String(metadata.name.clone()),
);
if let Some(ref description) = metadata.description {
metadata_obj.insert(
"description".to_string(),
serde_json::Value::String(description.clone()),
);
}
if let Some(ref icon) = metadata.icon {
metadata_obj
.insert("icon".to_string(), serde_json::Value::String(icon.clone()));
}
if !metadata.tags.is_empty() {
metadata_obj.insert(
"tags".to_string(),
serde_json::Value::Array(
metadata
.tags
.iter()
.map(|t| serde_json::Value::String(t.clone()))
.collect(),
),
);
}
if let Some(ref license) = metadata.license {
metadata_obj.insert(
"license".to_string(),
serde_json::Value::String(license.clone()),
);
}
}
if let Some(ref links) = manifest.links {
let mut links_obj = serde_json::Map::new();
if let Some(ref frontend) = links.frontend {
links_obj.insert(
"frontend".to_string(),
serde_json::Value::String(frontend.clone()),
);
}
if let Some(ref github) = links.github {
links_obj.insert(
"github".to_string(),
serde_json::Value::String(github.clone()),
);
}
if let Some(ref docs) = links.docs {
links_obj
.insert("docs".to_string(), serde_json::Value::String(docs.clone()));
}
if !links_obj.is_empty() {
metadata_obj
.insert("links".to_string(), serde_json::Value::Object(links_obj));
}
}
// Serialize metadata to JSON bytes
serde_json::to_vec(&serde_json::Value::Object(metadata_obj))?
};
// Install application with bundle blob_id and extracted metadata
return self.install_application(
&bundle_blob_id,
stored_size,
&uri,
bundle_metadata, // Use metadata extracted from bundle manifest
package,
version,
Some(&signer_id), // signer_id from manifest verification
true, // is_bundle: true for bundles
);
}
// Single WASM installation (existing behavior)
// For non-bundle installations, use defaults (package/version are not part of ApplicationId)
let package = "unknown";
let version = "0.0.0";
let (blob_id, size) = self
.add_blob(
response
.bytes_stream()
.map_err(io::Error::other)
.into_async_read(),
expected_size,
expected_hash,
)
.await?;
self.install_application(
&blob_id, size, &uri, metadata, package, version,
None, // signer_id: None for non-bundle installations
false, // is_bundle: false for single WASM
)
}
/// Install a bundle archive (.mpk - Mero Package Kit) containing WASM, ABI, and migrations
/// Note: metadata parameter is ignored for bundles - metadata is always extracted from manifest
async fn install_bundle_from_path(
&self,
path: Utf8PathBuf,
_metadata: Vec<u8>,
) -> eyre::Result<ApplicationId> {
debug!(
path = %path,
"install_bundle_from_path started"
);
// Clone path for deletion after installation
let bundle_path = path.clone();
// Read bundle file
let bundle_data = Arc::new(tokio::fs::read(&path).await?);
let bundle_size = bundle_data.len() as u64;
// Store entire bundle as a single blob
let cursor = Cursor::new(bundle_data.as_slice());
let (bundle_blob_id, stored_size) = self.add_blob(cursor, Some(bundle_size), None).await?;
debug!(
%bundle_blob_id,
bundle_size,
stored_size,
"bundle stored as blob"
);
// Extract bundle manifest and verify signature
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_data_clone = Arc::clone(&bundle_data);
let (verification, manifest) = tokio::task::spawn_blocking(move || {
Self::verify_and_extract_manifest(&bundle_data_clone)
})
.await??;
let signer_id = verification.signer_id;
// Extract package and version from manifest (ignore provided values)
let package = &manifest.package;
let version = &manifest.app_version;
// Extract artifacts with deduplication
// Use node root (parent of blobstore) instead of blobstore root
// Must be done before spawn_blocking
let blobstore_root = self.blobstore.root_path();
let node_root = blobstore_root
.parent()
.ok_or_else(|| eyre::eyre!("blobstore root has no parent"))?
.to_path_buf();
// Extract directory is derived from package and version
let extract_dir = node_root
.join("applications")
.join(package)
.join(version)
.join("extracted");
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_data_clone = Arc::clone(&bundle_data);
let manifest_clone = manifest.clone();
let extract_dir_clone = extract_dir.clone();
let node_root_clone = node_root.clone();
let package_clone = package.to_string();
let version_clone = version.to_string();
tokio::task::spawn_blocking(move || {
Self::extract_bundle_artifacts(
&bundle_data_clone,
&manifest_clone,
&extract_dir_clone,
&node_root_clone,
&package_clone,
&version_clone,
)
})
.await??;
let Ok(uri) = Url::from_file_path(path) else {
bail!("non-absolute path")
};
// Extract metadata from bundle manifest and serialize it
let bundle_metadata = {
let mut metadata_obj = serde_json::Map::new();
metadata_obj.insert(
"package".to_string(),
serde_json::Value::String(package.clone()),
);
metadata_obj.insert(
"version".to_string(),
serde_json::Value::String(version.clone()),
);
if let Some(ref metadata) = manifest.metadata {
metadata_obj.insert(
"name".to_string(),
serde_json::Value::String(metadata.name.clone()),
);
if let Some(ref description) = metadata.description {
metadata_obj.insert(
"description".to_string(),
serde_json::Value::String(description.clone()),
);
}
if let Some(ref icon) = metadata.icon {
metadata_obj
.insert("icon".to_string(), serde_json::Value::String(icon.clone()));
}
if !metadata.tags.is_empty() {
metadata_obj.insert(
"tags".to_string(),
serde_json::Value::Array(
metadata
.tags
.iter()
.map(|t| serde_json::Value::String(t.clone()))
.collect(),
),
);
}
if let Some(ref license) = metadata.license {
metadata_obj.insert(
"license".to_string(),
serde_json::Value::String(license.clone()),
);
}
}
if let Some(ref links) = manifest.links {
let mut links_obj = serde_json::Map::new();
if let Some(ref frontend) = links.frontend {
links_obj.insert(
"frontend".to_string(),
serde_json::Value::String(frontend.clone()),
);
}
if let Some(ref github) = links.github {
links_obj.insert(
"github".to_string(),
serde_json::Value::String(github.clone()),
);
}
if let Some(ref docs) = links.docs {
links_obj.insert("docs".to_string(), serde_json::Value::String(docs.clone()));
}
if !links_obj.is_empty() {
metadata_obj.insert("links".to_string(), serde_json::Value::Object(links_obj));
}
}
// Serialize metadata to JSON bytes
serde_json::to_vec(&serde_json::Value::Object(metadata_obj))?
};
// Install application with bundle blob_id and extracted metadata
let application_id = self.install_application(
&bundle_blob_id,
stored_size,
&uri.as_str().parse()?,
bundle_metadata, // Use metadata extracted from bundle manifest
package,
version,
Some(&signer_id), // signer_id from manifest verification
true, // is_bundle: true for bundles
)?;
// Delete bundle file after successful installation (it's now stored as a blob)
if let Err(e) = tokio::fs::remove_file(&bundle_path).await {
warn!(
path = %bundle_path,
error = %e,
"Failed to delete bundle file after installation"
);
// Don't fail installation if deletion fails - bundle is already installed
} else {
debug!(
path = %bundle_path,
"Deleted bundle file after successful installation"
);
}
Ok(application_id)
}
/// Validates that a string is safe for use as a filesystem path component.
/// Returns an error if the string contains path traversal or other unsafe characters.
///
/// This prevents malicious bundle manifests from writing files outside the intended
/// `applications` directory by using path traversal sequences in package or version fields.
fn validate_path_component(value: &str, field_name: &str) -> eyre::Result<()> {
// Check for parent directory traversal
if value.contains("..") {
bail!("{} contains path traversal sequence '..'", field_name);
}
// Check for directory separators (Unix and Windows)
if value.contains('/') || value.contains('\\') {
bail!("{} contains directory separator", field_name);
}
// Check for null bytes
if value.contains('\0') {
bail!("{} contains null byte", field_name);
}
// Check for absolute path indicators (Windows drive letters like "C:")
if value.len() >= 2 && value.as_bytes().get(1) == Some(&b':') {
bail!("{} appears to be an absolute path", field_name);
}
Ok(())
}
/// Validates that an artifact path is safe for use as a relative filesystem path.
/// Unlike `validate_path_component`, this allows subdirectories (forward slashes)
/// but still prevents path traversal attacks.
///
/// This prevents malicious bundle manifests from specifying artifact paths like
/// `../../../etc/passwd` that could escape the extraction directory.
fn validate_artifact_path(value: &str, field_name: &str) -> eyre::Result<()> {
if value.is_empty() {
bail!("{} is empty", field_name);
}
if value.contains('\0') {
bail!("{} contains null byte", field_name);
}
if value.contains('\\') {
bail!("{} contains backslash (use forward slashes)", field_name);
}
// Reject absolute paths: Unix-style `/` prefix or Windows drive letter (e.g., "C:")
if value.starts_with('/') {
bail!("{} is an absolute path", field_name);
}
if value.as_bytes().get(1) == Some(&b':') {
bail!("{} appears to be an absolute Windows path", field_name);
}
// Reject path traversal via ".." components
if value.split('/').any(|c| c == "..") {
bail!("{} contains path traversal component '..'", field_name);
}
Ok(())
}
/// Extracts bundle manifest, verifies signature, and returns both verification result and typed manifest.
/// This helper ensures all bundle installation paths go through the same verified flow.
fn verify_and_extract_manifest(
bundle_data: &[u8],
) -> eyre::Result<(ManifestVerification, BundleManifest)> {
let (manifest_json, manifest) = Self::extract_bundle_manifest(bundle_data)?;
let verification = verify_manifest_signature(&manifest_json)?;
debug!(
signer_id = %verification.signer_id,
bundle_hash = %hex::encode(verification.bundle_hash),
"bundle manifest signature verified"
);
Ok((verification, manifest))
}
/// Extract and parse bundle manifest from bundle archive data.
/// Returns both the raw JSON value (for signature verification) and the typed manifest.
fn extract_bundle_manifest(
bundle_data: &[u8],
) -> eyre::Result<(serde_json::Value, BundleManifest)> {
let tar = GzDecoder::new(bundle_data);
let mut archive = Archive::new(tar);
for entry in archive.entries()? {
let mut entry = entry?;
let path = entry.path()?;
if path.file_name().and_then(|n| n.to_str()) == Some("manifest.json") {
let mut manifest_str = String::new();
entry.read_to_string(&mut manifest_str)?;
// Parse as raw JSON value first (needed for signature verification)
// We need the raw JSON structure for canonicalization during signature verification
let manifest_json: serde_json::Value = serde_json::from_str(&manifest_str)
.map_err(|e| eyre::eyre!("failed to parse manifest.json as JSON: {}", e))?;
// Convert from already-parsed Value to typed manifest
// Note: from_value takes ownership, so we clone the Value here to preserve
// it for signature verification. This is necessary because canonicalization
// requires the exact JSON structure as parsed.
let manifest: BundleManifest = serde_json::from_value(manifest_json.clone())
.map_err(|e| eyre::eyre!("failed to parse manifest.json: {}", e))?;
// Validate required fields
if manifest.package.is_empty() {
bail!("bundle manifest 'package' field is empty");
}
if manifest.app_version.is_empty() {
bail!("bundle manifest 'appVersion' field is empty");
}
// Validate fields are safe for use in filesystem paths
// This prevents path traversal attacks where malicious manifests could
// write files outside the intended applications directory
Self::validate_path_component(&manifest.package, "package")?;
Self::validate_path_component(&manifest.app_version, "appVersion")?;
// Validate artifact paths to prevent path traversal attacks
// These paths are used to locate files within the extracted bundle
if let Some(ref wasm) = manifest.wasm {
Self::validate_artifact_path(&wasm.path, "wasm.path")?;
}
if let Some(ref abi) = manifest.abi {
Self::validate_artifact_path(&abi.path, "abi.path")?;
}
for (i, migration) in manifest.migrations.iter().enumerate() {
Self::validate_artifact_path(
&migration.path,
&format!("migrations[{}].path", i),
)?;
}
// Validate runtime version compatibility
let current_runtime_version = Version::parse(env!("CALIMERO_RELEASE_VERSION"))
.map_err(|e| eyre::eyre!("failed to parse current runtime version: {}", e))?;
let min_runtime_version =
Version::parse(&manifest.min_runtime_version).map_err(|e| {
eyre::eyre!(
"invalid minRuntimeVersion '{}': {}",
manifest.min_runtime_version,
e
)
})?;
if min_runtime_version > current_runtime_version {
bail!(
"bundle requires runtime version {} but current runtime is {}",
min_runtime_version,
current_runtime_version
);
}
return Ok((manifest_json, manifest));
}
}
bail!("manifest.json not found in bundle")
}
/// Check if a blob contains a bundle archive by peeking at the first few entries.
/// This is a lightweight check that only reads the archive structure, not the full content.
///
/// Returns true if manifest.json is found, false otherwise.
/// Logs warnings for parsing errors to help diagnose corrupted bundles.
pub fn is_bundle_blob(blob_bytes: &[u8]) -> bool {
// Quick check: try to parse as gzip/tar and look for manifest.json
let tar = GzDecoder::new(blob_bytes);
let mut archive = Archive::new(tar);
// Only check first 10 entries to avoid reading entire archive
let entries = match archive.entries() {
Ok(entries) => entries,
Err(e) => {
warn!(
"Failed to read tar archive entries (possible corruption): {}",
e
);
return false;
}
};
for (i, entry_result) in entries.enumerate() {
if i >= 10 {
break; // Give up after 10 entries
}
match entry_result {
Ok(entry) => {
match entry.path() {
Ok(path) => {
if path.file_name().and_then(|n| n.to_str()) == Some("manifest.json") {
return true;
}
}
Err(e) => {
warn!("Failed to read entry path in tar archive (possible corruption): {}", e);
// Continue checking other entries
}
}
}
Err(e) => {
warn!(
"Failed to read tar archive entry (possible corruption): {}",
e
);
// Continue checking other entries
}
}
}
false
}
/// Install an application from a bundle blob that's already in the blobstore.
/// This is used when a bundle blob is received via blob sharing or discovery.
/// No metadata needed - bundle detection happens via is_bundle_blob()
pub async fn install_application_from_bundle_blob(
&self,
blob_id: &BlobId,
source: &ApplicationSource,
) -> eyre::Result<ApplicationId> {
debug!(
%blob_id,
"install_application_from_bundle_blob started"
);
// Get bundle bytes from blobstore
let Some(bundle_bytes) = self.get_blob_bytes(blob_id, None).await? else {
bail!("bundle blob not found");
};
// Extract manifest and verify signature
// No metadata needed - bundle detection happens via is_bundle_blob()
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_bytes_clone = Arc::clone(&bundle_bytes);
let (verification, manifest) = tokio::task::spawn_blocking(move || {
Self::verify_and_extract_manifest(&bundle_bytes_clone)
})
.await??;
let signer_id = verification.signer_id;
let package = &manifest.package;
let version = &manifest.app_version;
// Extract artifacts with deduplication
// Must be done before spawn_blocking
let blobstore_root = self.blobstore.root_path();
let node_root = blobstore_root
.parent()
.ok_or_else(|| eyre::eyre!("blobstore root has no parent"))?
.to_path_buf();
let extract_dir = node_root
.join("applications")
.join(package)
.join(version)
.join("extracted");
// Wrap blocking I/O in spawn_blocking to avoid blocking async runtime
let bundle_bytes_clone = Arc::clone(&bundle_bytes);
let manifest_clone = manifest.clone();
let extract_dir_clone = extract_dir.clone();
let node_root_clone = node_root.clone();
let package_clone = package.to_string();
let version_clone = version.to_string();
tokio::task::spawn_blocking(move || {
Self::extract_bundle_artifacts(
&bundle_bytes_clone,
&manifest_clone,
&extract_dir_clone,
&node_root_clone,
&package_clone,
&version_clone,
)
})
.await??;
let size = bundle_bytes.len() as u64;
debug!(
%blob_id,
package,
version,
size,
"bundle extracted and ready for installation"
);
// Extract metadata from bundle manifest and serialize it
let bundle_metadata = {
let mut metadata_obj = serde_json::Map::new();
metadata_obj.insert(
"package".to_string(),
serde_json::Value::String(package.clone()),
);
metadata_obj.insert(
"version".to_string(),
serde_json::Value::String(version.clone()),
);
if let Some(ref metadata) = manifest.metadata {
metadata_obj.insert(
"name".to_string(),
serde_json::Value::String(metadata.name.clone()),
);
if let Some(ref description) = metadata.description {
metadata_obj.insert(
"description".to_string(),
serde_json::Value::String(description.clone()),
);
}
if let Some(ref icon) = metadata.icon {
metadata_obj
.insert("icon".to_string(), serde_json::Value::String(icon.clone()));
}
if !metadata.tags.is_empty() {
metadata_obj.insert(
"tags".to_string(),
serde_json::Value::Array(
metadata
.tags
.iter()
.map(|t| serde_json::Value::String(t.clone()))
.collect(),
),
);
}
if let Some(ref license) = metadata.license {
metadata_obj.insert(
"license".to_string(),
serde_json::Value::String(license.clone()),
);
}
}
if let Some(ref links) = manifest.links {
let mut links_obj = serde_json::Map::new();
if let Some(ref frontend) = links.frontend {
links_obj.insert(
"frontend".to_string(),
serde_json::Value::String(frontend.clone()),
);
}
if let Some(ref github) = links.github {
links_obj.insert(
"github".to_string(),
serde_json::Value::String(github.clone()),
);
}
if let Some(ref docs) = links.docs {
links_obj.insert("docs".to_string(), serde_json::Value::String(docs.clone()));
}
if !links_obj.is_empty() {
metadata_obj.insert("links".to_string(), serde_json::Value::Object(links_obj));
}
}
// Serialize metadata to JSON bytes
serde_json::to_vec(&serde_json::Value::Object(metadata_obj))?
};
// Install application with extracted metadata
self.install_application(
blob_id,
size,
source,
bundle_metadata,
package,
version,
Some(&signer_id), // signer_id from manifest verification
true, // is_bundle: true for bundles
)
}
/// Find duplicate artifact in other versions by hash and relative path
/// Only matches files with the same relative path within the bundle to avoid
/// collisions between files with the same name in different directories
fn find_duplicate_artifact(
node_root: &Utf8Path,
package: &str,
current_version: &str,
hash: &[u8; 32],
relative_path: &str,
) -> Option<Utf8PathBuf> {
// Check other versions for the same hash at the same relative path
let package_dir = node_root.join("applications").join(package);
if let Ok(entries) = fs::read_dir(package_dir.as_std_path()) {
for entry in entries.flatten() {
if let Ok(version_name) = entry.file_name().into_string() {
if version_name == current_version {
continue; // Skip current version
}
// Check extracted directory in this version at the same relative path
let extracted_dir = package_dir.join(&version_name).join("extracted");
let candidate_path = extracted_dir.join(relative_path);
if candidate_path.exists() {
// Compute hash of candidate file
if let Ok(candidate_content) = fs::read(candidate_path.as_std_path()) {
let candidate_hash = Sha256::digest(&candidate_content);
let candidate_array: [u8; 32] = candidate_hash.into();
if candidate_array == *hash {
return Some(candidate_path);
}
}
}
}
}
}
None
}
/// Extract bundle artifacts with deduplication
///
/// This function is synchronized per package-version to prevent race conditions
/// when multiple concurrent calls try to extract the same bundle.
fn extract_bundle_artifacts(
bundle_data: &[u8],
_manifest: &BundleManifest,
extract_dir: &Utf8Path,
node_root: &Utf8Path,
package: &str,
current_version: &str,
) -> eyre::Result<()> {
// Create extraction directory
fs::create_dir_all(extract_dir)?;
// Use a lock file to prevent concurrent extraction of the same bundle version
// Lock file path: extract_dir/.extracting.lock
let lock_file_path = extract_dir.join(".extracting.lock");
let marker_file_path = extract_dir.join(".extracted");
// Check if extraction is already complete
// Only skip if marker exists AND the expected WASM file exists
// This handles the case where files were deleted but marker remains
if marker_file_path.exists() {
// Check if WASM file exists (using manifest to determine path)
// If marker exists but WASM doesn't, marker is stale - remove it and re-extract
let wasm_relative_path = _manifest
.wasm
.as_ref()
.map(|w| w.path.as_str())
.unwrap_or("app.wasm");
// Validate WASM path to prevent path traversal attacks before checking existence
if wasm_relative_path.contains("..") {
bail!(
"WASM path traversal detected in manifest: {} contains '..' component",
wasm_relative_path
);
}
let wasm_path = extract_dir.join(wasm_relative_path);
// Additional validation: ensure the resolved path stays within extract_dir
if wasm_path.exists() {
// Validate path traversal even if file exists
let canonical_wasm = wasm_path.canonicalize_utf8()?;
// extract_dir might not exist if wasm_relative_path contains subdirectories
// Reconstruct canonical extract_dir from wasm_path by removing relative path components
let canonical_extract = if extract_dir.exists() {
extract_dir.canonicalize_utf8()?
} else {
// Reconstruct extract_dir from wasm_path by removing wasm_relative_path components
// Since we validated wasm_relative_path doesn't contain "..", this is safe
let wasm_parent = wasm_path
.parent()
.ok_or_else(|| eyre::eyre!("WASM path has no parent directory"))?;
let wasm_parent_canonical = wasm_parent.canonicalize_utf8()?;
// Count depth of wasm_relative_path (number of path components)
let relative_depth = wasm_relative_path
.split('/')
.filter(|s| !s.is_empty())
.count()
.saturating_sub(1); // Subtract 1 for the filename itself
// Go up relative_depth levels from wasm_parent to get extract_dir
let mut canonical_extract_candidate = wasm_parent_canonical.clone();
for _ in 0..relative_depth {
if let Some(parent) = canonical_extract_candidate.parent() {
canonical_extract_candidate = parent.to_path_buf();
} else {
bail!("Cannot reconstruct extract_dir from WASM path");
}
}
canonical_extract_candidate.try_into().map_err(|_| {
eyre::eyre!("Failed to convert extract_dir path to Utf8PathBuf")
})?
};
if !canonical_wasm.starts_with(&canonical_extract) {
bail!(
"WASM path traversal detected: {} escapes extraction directory {}",
wasm_relative_path,
extract_dir
);
}
debug!(
package,
version = current_version,
"Bundle already extracted (marker file and WASM exist), skipping"
);
return Ok(());
} else {
// Marker exists but WASM doesn't - remove stale marker and re-extract
debug!(
package,
version = current_version,
"Marker file exists but WASM not found, removing stale marker"
);
let _ = fs::remove_file(&marker_file_path);
}
}
// Try to acquire exclusive lock by creating lock file atomically
// create_new() is atomic - fails if file exists (works on Unix and Windows)
let lock_acquired = match std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(lock_file_path.as_std_path())
{
Ok(_) => {
// Lock file created - we're the first to extract
true
}
Err(_) => {
// Lock file already exists - another extraction is in progress
// Wait and check if extraction completes
for _ in 0..20 {
std::thread::sleep(std::time::Duration::from_millis(100));
if marker_file_path.exists() {
debug!(
package,
version = current_version,
"Bundle extraction completed by another process"
);
return Ok(());
}
}
// If marker still doesn't exist after waiting, proceed anyway
// (lock file might be stale from crashed process)
warn!(
package,
version = current_version,
"Lock file exists but extraction not complete, proceeding anyway"
);
false
}
};
// Track if we created a lock file that needs cleanup
let mut lock_created_by_us = lock_acquired;
// Only proceed with extraction if we acquired the lock
// (or if lock is stale and we're proceeding anyway)
if !lock_acquired {
// Try to remove stale lock and retry
let _ = fs::remove_file(&lock_file_path);
// Check marker one more time
if marker_file_path.exists() {
return Ok(());
}
// Create lock file again - handle race condition where another thread
// might have created it between removal and this creation
match std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(lock_file_path.as_std_path())
{
Ok(_) => {
// Successfully acquired lock, proceed with extraction
lock_created_by_us = true;
}
Err(_) => {
// Another thread created the lock between removal and creation
// Wait briefly and check if extraction completed
std::thread::sleep(std::time::Duration::from_millis(100));
if marker_file_path.exists() {
debug!(
package,
version = current_version,
"Bundle extraction completed by another process after lock retry"
);
return Ok(());
}
// If marker still doesn't exist, the other thread is still extracting
// Return error to avoid concurrent extraction
bail!(
"Failed to acquire extraction lock after retry - another process is extracting"
);
}
}
}
// Ensure lock file is cleaned up even if extraction fails
// Use a guard to clean up on early return or error
struct LockGuard {
path: Utf8PathBuf,
should_remove: std::cell::Cell<bool>,
}
impl Drop for LockGuard {
fn drop(&mut self) {
if self.should_remove.get() {
let _ = fs::remove_file(&self.path);
}
}
}
let lock_guard = LockGuard {
path: lock_file_path.clone(),
should_remove: std::cell::Cell::new(lock_created_by_us),
};
let tar = GzDecoder::new(bundle_data);
let mut archive = Archive::new(tar);
// Extract all files from bundle
for entry_result in archive.entries()? {
let mut entry = entry_result?;
// Extract path_bytes first, converting to owned to drop borrow
let path_bytes_owned = {
let header = entry.header();
header.path_bytes().into_owned()
};
let relative_path = {
let path_str = std::str::from_utf8(&path_bytes_owned)
.map_err(|_| eyre::eyre!("invalid UTF-8 in file path"))?;
path_str.to_string()
};
// Skip macOS resource fork files (._* files)
// Check filename component, not full path, to catch files in subdirectories
if let Some(file_name) = std::path::Path::new(&relative_path)
.file_name()
.and_then(|n| n.to_str())
{
if file_name.starts_with("._") {
continue;
}
}
// Read content (header borrow is dropped)
let mut content = Vec::new();
std::io::copy(&mut entry, &mut content)?;
// Preserve directory structure from bundle
let dest_path = extract_dir.join(&relative_path);
// Validate path to prevent path traversal attacks
// Check that the relative path doesn't contain ".." components that would escape
if relative_path.contains("..") {
bail!(
"Path traversal detected: {} contains '..' component",
relative_path
);
}
// Additional validation: ensure the resolved path stays within extract_dir
// Always validate by constructing expected path, regardless of whether it exists
// This prevents path traversal even when parent directories don't exist yet
let canonical_extract = extract_dir.canonicalize_utf8()?;
// Construct what the canonical dest_path should be
// Since we already checked relative_path doesn't contain "..",
// joining extract_dir with relative_path is safe
let expected_dest = canonical_extract.join(&relative_path);
// Verify the expected path stays within extract_dir
// This works even if the path doesn't exist yet because we're constructing
// it from the canonical extract_dir and a validated relative_path
if !expected_dest.starts_with(&canonical_extract) {
bail!(
"Path traversal detected: {} would escape extraction directory {}",
relative_path,
extract_dir
);
}
// If dest_path exists, also verify the actual canonicalized path matches expected
if dest_path.exists() {
let canonical_dest = dest_path.canonicalize_utf8()?;
if !canonical_dest.starts_with(&canonical_extract) {
bail!(
"Path traversal detected: {} escapes extraction directory {}",
relative_path,
extract_dir
);
}
}
// Create parent directories if needed
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
// Compute hash
let hash = Sha256::digest(&content);
let hash_array: [u8; 32] = hash.into();
// Check for duplicates in other versions at the same relative path
if let Some(duplicate_path) = Self::find_duplicate_artifact(
node_root,
package,
current_version,
&hash_array,
&relative_path,
) {
// Create hardlink to duplicate file
if let Err(e) = fs::hard_link(duplicate_path.as_std_path(), dest_path.as_std_path())
{
// If hardlink fails (e.g., cross-filesystem), fall back to copying
warn!(
file = %relative_path,
duplicate = %duplicate_path,
error = %e,
"hardlink failed, copying instead"
);
fs::write(&dest_path, &content)?;
} else {
debug!(
file = %relative_path,
hash = hex::encode(hash),
duplicate = %duplicate_path,
"deduplicated artifact via hardlink"
);
}
} else {
// No duplicate found, write new file
fs::write(&dest_path, &content)?;
debug!(
file = %relative_path,
hash = hex::encode(hash),
"extracted artifact"
);
}
}
// Write marker file to indicate extraction is complete
fs::write(&marker_file_path, b"extracted")?;
// Remove lock file explicitly on success (guard will skip removal if we already did it)
if lock_guard.should_remove.get() {
let _ = fs::remove_file(&lock_file_path);
lock_guard.should_remove.set(false); // Prevent guard from removing it again
}
Ok(())
}
pub fn uninstall_application(&self, application_id: &ApplicationId) -> eyre::Result<()> {
let mut handle = self.datastore.handle();
let key = key::ApplicationMeta::new(*application_id);
// Get application metadata before deleting to check if it's a bundle
let application_meta = handle.get(&key)?;
// Delete the ApplicationMeta entry
handle.delete(&key)?;
// Clean up extracted bundle files if this is a bundle
if let Some(application) = application_meta {
// Check if this is a bundle by checking package/version
// Bundles have meaningful package/version (not "unknown"/"0.0.0")
let is_bundle = application.package.as_ref() != "unknown"
&& application.version.as_ref() != "0.0.0";
if is_bundle {
// Construct path to extracted bundle directory
let blobstore_root = self.blobstore.root_path();
let node_root = blobstore_root
.parent()
.ok_or_else(|| eyre::eyre!("blobstore root has no parent"))?;
let bundle_dir = node_root
.join("applications")
.join(application.package.as_ref())
.join(application.version.as_ref());
// Delete the entire version directory (includes extracted/ subdirectory)
if bundle_dir.exists() {
debug!(
package = %application.package,
version = %application.version,
path = %bundle_dir,
"Removing extracted bundle directory"
);
if let Err(e) = fs::remove_dir_all(bundle_dir.as_std_path()) {
warn!(
package = %application.package,
version = %application.version,
path = %bundle_dir,
error = %e,
"Failed to remove extracted bundle directory"
);
// Don't fail uninstallation if cleanup fails - metadata is already deleted
} else {
debug!(
package = %application.package,
version = %application.version,
"Successfully removed extracted bundle directory"
);
}
// Also try to remove parent package directory if it's empty
let package_dir = node_root
.join("applications")
.join(application.package.as_ref());
if package_dir.exists() {
// Check if package directory is empty
if let Ok(mut entries) = fs::read_dir(package_dir.as_std_path()) {
if entries.next().is_none() {
// Directory is empty, remove it
if let Err(e) = fs::remove_dir(package_dir.as_std_path()) {
debug!(
package = %application.package,
error = %e,
"Failed to remove empty package directory (non-fatal)"
);
}
}
}
}
}
}
}
Ok(())
}
pub fn list_applications(&self) -> eyre::Result<Vec<Application>> {
let handle = self.datastore.handle();
let mut iter = handle.iter::<key::ApplicationMeta>()?;
let mut applications = vec![];
for (id, app) in iter.entries() {
let (id, app) = (id?, app?);
applications.push(Application::new(
id.application_id(),
ApplicationBlob {
bytecode: app.bytecode.blob_id(),
compiled: app.compiled.blob_id(),
},
app.size,
app.source.parse()?,
app.metadata.to_vec(),
));
}
Ok(applications)
}
pub fn update_compiled_app(
&self,
application_id: &ApplicationId,
compiled_blob_id: &BlobId,
) -> eyre::Result<()> {
let mut handle = self.datastore.handle();
let key = key::ApplicationMeta::new(*application_id);
let Some(mut application) = handle.get(&key)? else {
bail!("application not found");
};
application.compiled = key::BlobMeta::new(*compiled_blob_id);
handle.put(&key, &application)?;
Ok(())
}
/// List all packages
pub fn list_packages(&self) -> eyre::Result<Vec<String>> {
let handle = self.datastore.handle();
let mut iter = handle.iter::<key::ApplicationMeta>()?;
let mut packages = std::collections::HashSet::new();
for (id, app) in iter.entries() {
let (_, app) = (id?, app?);
let _ = packages.insert(app.package.to_string());
}
Ok(packages.into_iter().collect())
}
/// List all versions of a package
pub fn list_versions(&self, package: &str) -> eyre::Result<Vec<String>> {
let handle = self.datastore.handle();
let mut iter = handle.iter::<key::ApplicationMeta>()?;
let mut versions = Vec::new();
for (id, app) in iter.entries() {
let (_, app) = (id?, app?);
if app.package.as_ref() == package {
versions.push(app.version.to_string());
}
}
Ok(versions)
}
/// Get the latest version of a package (version string and application id)
pub fn get_latest_version(
&self,
package: &str,
) -> eyre::Result<Option<(String, ApplicationId)>> {
let handle = self.datastore.handle();
let mut iter = handle.iter::<key::ApplicationMeta>()?;
let mut latest_version: Option<(String, ApplicationId)> = None;
for (id, app) in iter.entries() {
let (id, app) = (id?, app?);
if app.package.as_ref() == package {
let version_str = app.version.to_string();
match &latest_version {
None => latest_version = Some((version_str, id.application_id())),
Some((current_version_str, _)) => {
// Try semantic version comparison first
let is_newer = match (
Version::parse(&version_str),
Version::parse(current_version_str),
) {
(Ok(new_version), Ok(current_version)) => {
// Both are valid semantic versions - use proper comparison
new_version > current_version
}
(Ok(_), Err(_)) => {
// New version is valid semver, current is not - prefer semver
true
}
(Err(_), Ok(_)) => {
// Current version is valid semver, new is not - keep current
false
}
(Err(_), Err(_)) => {
// Neither is valid semver - fall back to lexicographic comparison
version_str > *current_version_str
}
};
if is_newer {
latest_version = Some((version_str, id.application_id()));
}
}
}
}
}
Ok(latest_version)
}
/// Install application by package and version
pub async fn install_by_package_version(
&self,
_package: &str,
_version: &str,
source: &ApplicationSource,
metadata: Vec<u8>,
) -> eyre::Result<ApplicationId> {
// For now, we'll use the source URL to download the application
// In a real implementation, you might want to resolve the package/version to a URL
let url = source.to_string().parse()?;
self.install_application_from_url(url, metadata, None).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_path_component_valid() {
let valid_paths = vec!["com.example.app", "my-app", "my_app_v2", "app123"];
for path in valid_paths {
assert!(
NodeClient::validate_path_component(path, "test").is_ok(),
"Valid path '{}' should pass validation",
path
);
}
}
#[test]
fn test_validate_path_component_path_traversal() {
let invalid_paths = vec!["../etc", "..", "foo/../bar", "package..name"];
for path in invalid_paths {
assert!(
NodeClient::validate_path_component(path, "test").is_err(),
"Path traversal '{}' should be rejected",
path
);
}
}
#[test]
fn test_validate_path_component_directory_separators() {
let invalid_paths = vec!["foo/bar", "foo\\bar", "/absolute", "\\windows"];
for path in invalid_paths {
assert!(
NodeClient::validate_path_component(path, "test").is_err(),
"Path with separator '{}' should be rejected",
path
);
}
}
#[test]
fn test_validate_path_component_null_byte() {
let invalid_path = "package\0name";
assert!(
NodeClient::validate_path_component(invalid_path, "test").is_err(),
"Path with null byte should be rejected"
);
}
#[test]
fn test_validate_path_component_windows_drive() {
let invalid_paths = vec!["C:malicious", "D:path"];
for path in invalid_paths {
assert!(
NodeClient::validate_path_component(path, "test").is_err(),
"Windows drive path '{}' should be rejected",
path
);
}
}
#[test]
fn test_validate_path_component_unicode_separator() {
// Test Unicode path separator (full-width slash)
let invalid_path = "package/name";
// Note: This might pass current validation, but documents the limitation
// The current implementation checks for ASCII '/' and '\' only
}
#[test]
fn test_validate_artifact_path_valid() {
let valid_paths = vec!["app.wasm", "src/main.wasm", "migrations/001_init.sql"];
for path in valid_paths {
assert!(
NodeClient::validate_artifact_path(path, "test").is_ok(),
"Valid artifact path '{}' should pass validation",
path
);
}
}
#[test]
fn test_validate_artifact_path_empty() {
assert!(
NodeClient::validate_artifact_path("", "test").is_err(),
"Empty path should be rejected"
);
}
#[test]
fn test_validate_artifact_path_null_byte() {
let invalid_path = "app\0.wasm";
assert!(
NodeClient::validate_artifact_path(invalid_path, "test").is_err(),
"Path with null byte should be rejected"
);
}
#[test]
fn test_validate_artifact_path_backslash() {
let invalid_path = "app\\main.wasm";
assert!(
NodeClient::validate_artifact_path(invalid_path, "test").is_err(),
"Path with backslash should be rejected"
);
}
#[test]
fn test_validate_artifact_path_absolute_unix() {
let invalid_path = "/etc/passwd";
assert!(
NodeClient::validate_artifact_path(invalid_path, "test").is_err(),
"Absolute Unix path should be rejected"
);
}
#[test]
fn test_validate_artifact_path_absolute_windows() {
let invalid_paths = vec!["C:malicious", "D:path\\file.wasm"];
for path in invalid_paths {
assert!(
NodeClient::validate_artifact_path(path, "test").is_err(),
"Windows absolute path '{}' should be rejected",
path
);
}
}
#[test]
fn test_validate_artifact_path_traversal() {
let invalid_paths = vec!["../etc/passwd", "foo/../bar", "..", "migrations/../../etc"];
for path in invalid_paths {
assert!(
NodeClient::validate_artifact_path(path, "test").is_err(),
"Path traversal '{}' should be rejected",
path
);
}
}
#[test]
fn test_validate_artifact_path_url_encoded() {
// Test URL-encoded path traversal attempts
let invalid_path = "..%2Fetc";
// Note: Current implementation doesn't decode URL encoding
// This test documents that URL-encoded sequences would need to be decoded first
// The path "..%2Fetc" would be treated as a literal string and might pass
}
#[test]
fn test_validate_artifact_path_very_long() {
// Test with a very long path (potential DoS)
// Current implementation doesn't check length, so very long paths pass validation
let long_path = "a".repeat(10000);
assert!(
NodeClient::validate_artifact_path(&long_path, "test").is_ok(),
"Very long path currently passes validation (no length check implemented)"
);
}
}