-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.rs
More file actions
1366 lines (1223 loc) · 48.1 KB
/
github.rs
File metadata and controls
1366 lines (1223 loc) · 48.1 KB
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
use crate::backend::SecurityFeature;
use crate::backend::VersionInfo;
use crate::backend::asset_matcher::{self, Asset, ChecksumFetcher};
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::{
get_filename_from_url, install_artifact, lookup_platform_key, lookup_platform_key_for_target,
template_string, try_with_v_prefix, verify_artifact,
};
use crate::cli::args::{BackendArg, ToolVersionType};
use crate::config::{Config, Settings};
use crate::env;
use crate::file;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::ToolVersionOptions;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::{backend::Backend, forgejo, github, gitlab};
use async_trait::async_trait;
use eyre::Result;
use regex::Regex;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::sync::Arc;
#[derive(Debug)]
pub struct UnifiedGitBackend {
ba: Arc<BackendArg>,
}
struct ReleaseAsset {
name: String,
url: String,
url_api: String,
digest: Option<String>,
}
const DEFAULT_GITHUB_API_BASE_URL: &str = "https://api.github.com";
const DEFAULT_GITLAB_API_BASE_URL: &str = "https://gitlab.com/api/v4";
const DEFAULT_FORGEJO_API_BASE_URL: &str = "https://codeberg.org/api/v1";
/// Status returned from verification attempts
enum VerificationStatus {
/// No attestations or provenance found (not an error, tool may not have them)
NoAttestations,
/// An error occurred during verification
Error(String),
}
/// Returns install-time-only option keys for GitHub/GitLab backend.
pub fn install_time_option_keys() -> Vec<String> {
vec![
"asset_pattern".into(),
"url".into(),
"version_prefix".into(),
]
}
#[async_trait]
impl Backend for UnifiedGitBackend {
fn get_type(&self) -> BackendType {
if self.is_gitlab() {
BackendType::Gitlab
} else if self.is_forgejo() {
BackendType::Forgejo
} else {
BackendType::Github
}
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<SecurityFeature> {
// Only report security features for GitHub (not GitLab yet)
if self.is_gitlab() || self.is_forgejo() {
return vec![];
}
let mut features = vec![];
// Get the latest release to check for security assets
let repo = self.ba.tool_name();
let opts = self.ba.opts();
let api_url = self.get_api_url(&opts);
let releases = github::list_releases_from_url(api_url.as_str(), &repo)
.await
.unwrap_or_default();
let latest_release = releases.first();
// Check for checksum files in assets
if let Some(release) = latest_release {
let has_checksum = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains("sha256")
|| name.contains("checksum")
|| name.ends_with(".sha256")
|| name.ends_with(".sha512")
});
if has_checksum {
features.push(SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
});
}
}
// Check for GitHub Attestations (assets with .sigstore.json or .sigstore extension)
if let Some(release) = latest_release {
let has_attestations = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.ends_with(".sigstore.json") || name.ends_with(".sigstore")
});
if has_attestations {
features.push(SecurityFeature::GithubAttestations {
signer_workflow: None,
});
}
}
// Check for SLSA provenance (intoto.jsonl files)
if let Some(release) = latest_release {
let has_slsa = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains(".intoto.jsonl")
|| name.contains("provenance")
|| name.ends_with(".attestation")
});
if has_slsa {
features.push(SecurityFeature::Slsa { level: None });
}
}
features
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let repo = self.ba.tool_name();
let id = self.ba.to_string();
let opts = self.ba.opts();
let api_url = self.get_api_url(&opts);
let version_prefix = opts.get("version_prefix");
// Derive web URL base from API URL for enterprise support
let web_url_base = if self.is_gitlab() {
if api_url == DEFAULT_GITLAB_API_BASE_URL {
format!("https://gitlab.com/{}", repo)
} else {
// Enterprise GitLab - derive web URL from API URL
let web_url = api_url.replace("/api/v4", "");
format!("{}/{}", web_url, repo)
}
} else if self.is_forgejo() {
if api_url == DEFAULT_FORGEJO_API_BASE_URL {
format!("https://codeberg.org/{}", repo)
} else {
// Enterprise Forgejo - derive web URL from API URL
let web_url = api_url.replace("/api/v1", "");
format!("{}/{}", web_url, repo)
}
} else if api_url == DEFAULT_GITHUB_API_BASE_URL {
format!("https://github.com/{}", repo)
} else {
// Enterprise GitHub - derive web URL from API URL
let web_url = api_url.replace("/api/v3", "").replace("api.", "");
format!("{}/{}", web_url, repo)
};
// Get releases with full metadata from GitHub or GitLab
let raw_versions: Vec<VersionInfo> = if self.is_gitlab() {
gitlab::list_releases_from_url(api_url.as_str(), &repo)
.await?
.into_iter()
.filter(|r| version_prefix.is_none_or(|p| r.tag_name.starts_with(p)))
.map(|r| VersionInfo {
version: self.strip_version_prefix(&r.tag_name),
created_at: r.released_at,
release_url: Some(format!("{}/-/releases/{}", web_url_base, r.tag_name)),
..Default::default()
})
.collect()
} else if self.is_forgejo() {
forgejo::list_releases_from_url(api_url.as_str(), &repo)
.await?
.into_iter()
.filter(|r| version_prefix.is_none_or(|p| r.tag_name.starts_with(p)))
.map(|r| VersionInfo {
version: self.strip_version_prefix(&r.tag_name),
created_at: Some(r.created_at),
release_url: Some(format!("{}/releases/tag/{}", web_url_base, r.tag_name)),
..Default::default()
})
.collect()
} else {
github::list_releases_from_url(api_url.as_str(), &repo)
.await?
.into_iter()
.filter(|r| version_prefix.is_none_or(|p| r.tag_name.starts_with(p)))
.map(|r| VersionInfo {
version: self.strip_version_prefix(&r.tag_name),
created_at: Some(r.created_at),
release_url: Some(format!("{}/releases/tag/{}", web_url_base, r.tag_name)),
..Default::default()
})
.collect()
};
// Apply common validation and reverse order
let versions = raw_versions
.into_iter()
.filter(|v| match v.version.parse::<ToolVersionType>() {
Ok(ToolVersionType::Version(_)) => true,
_ => {
warn!("Invalid version: {id}@{}", v.version);
false
}
})
.rev()
.collect();
Ok(versions)
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
let repo = self.repo();
let opts = tv.request.options();
let api_url = self.get_api_url(&opts);
// Check if URL already exists in lockfile platforms first
let platform_key = self.get_platform_key();
let asset = if let Some(existing_platform) = tv.lock_platforms.get(&platform_key)
&& existing_platform.url.is_some()
{
debug!(
"Using existing URL from lockfile for platform {}: {}",
platform_key,
existing_platform.url.clone().unwrap_or_default()
);
ReleaseAsset {
name: get_filename_from_url(existing_platform.url.as_deref().unwrap_or("")),
url: existing_platform.url.clone().unwrap_or_default(),
url_api: existing_platform.url_api.clone().unwrap_or_default(),
digest: None, // Don't use old digest from lockfile, will be fetched fresh if needed
}
} else {
// Find the asset URL for this specific version
self.resolve_asset_url(&tv, &opts, &repo, &api_url).await?
};
// Download and install
self.download_and_install(ctx, &mut tv, &asset, &opts)
.await?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<std::path::PathBuf>> {
if self.get_filter_bins(tv).is_some() {
return Ok(vec![tv.install_path().join(".mise-bins")]);
}
self.discover_bin_paths(tv)
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// These options affect which artifact is downloaded
for key in ["asset_pattern", "url", "version_prefix"] {
if let Some(value) = opts.get(key) {
result.insert(key.to_string(), value.clone());
}
}
result
}
/// Resolve platform-specific lock information for cross-platform lockfile generation.
/// This fetches release asset metadata including SHA256 digests from GitHub/GitLab API.
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let repo = self.repo();
let opts = tv.request.options();
let api_url = self.get_api_url(&opts);
// Resolve asset for the target platform
let asset = self
.resolve_asset_url_for_target(tv, &opts, &repo, &api_url, target)
.await;
match asset {
Ok(asset) => Ok(PlatformInfo {
url: Some(asset.url),
url_api: Some(asset.url_api),
checksum: asset.digest,
size: None,
conda_deps: None,
}),
Err(e) => {
debug!(
"Failed to resolve asset for {} on {}: {}",
self.ba.full(),
target.to_key(),
e
);
Ok(PlatformInfo::default())
}
}
}
}
impl UnifiedGitBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
fn is_gitlab(&self) -> bool {
self.ba.backend_type() == BackendType::Gitlab
}
fn is_forgejo(&self) -> bool {
self.ba.backend_type() == BackendType::Forgejo
}
fn repo(&self) -> String {
// Use tool_name() method to properly resolve aliases
// This ensures that when an alias like "test-edit = github:microsoft/edit" is used,
// the repository name is correctly extracted as "microsoft/edit"
self.ba.tool_name()
}
// Helper to format asset names for error messages
fn format_asset_list<'a, I>(assets: I) -> String
where
I: Iterator<Item = &'a String>,
{
assets.cloned().collect::<Vec<_>>().join(", ")
}
fn get_api_url(&self, opts: &ToolVersionOptions) -> String {
opts.get("api_url")
.map(|s| s.as_str())
.unwrap_or(if self.is_gitlab() {
DEFAULT_GITLAB_API_BASE_URL
} else if self.is_forgejo() {
DEFAULT_FORGEJO_API_BASE_URL
} else {
DEFAULT_GITHUB_API_BASE_URL
})
.to_string()
}
/// Downloads and installs the asset
async fn download_and_install(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
asset: &ReleaseAsset,
opts: &ToolVersionOptions,
) -> Result<()> {
let filename = asset.name.clone();
let file_path = tv.download_path().join(&filename);
// Count operations dynamically:
// 1. Download (always)
// 2. Verify checksum (if checksum option present)
// 3. Extract/install (if file needs extraction)
let mut op_count = 1; // download
// Check if we'll verify checksum
let has_checksum = lookup_platform_key(opts, "checksum")
.or_else(|| opts.get("checksum").cloned())
.is_some();
if has_checksum {
op_count += 1;
}
// Check if we'll extract (archives need extraction)
let needs_extraction = filename.ends_with(".tar.gz")
|| filename.ends_with(".tar.xz")
|| filename.ends_with(".tar.bz2")
|| filename.ends_with(".tar.zst")
|| filename.ends_with(".tar")
|| filename.ends_with(".tgz")
|| filename.ends_with(".txz")
|| filename.ends_with(".tbz2")
|| filename.ends_with(".zip");
if needs_extraction {
op_count += 1;
}
ctx.pr.start_operations(op_count);
// Store the asset URL and digest (if available) in the tool version
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(asset.url.clone());
platform_info.url_api = Some(asset.url_api.clone());
if let Some(digest) = &asset.digest {
debug!("using GitHub API digest for checksum verification");
platform_info.checksum = Some(digest.clone());
}
let url = match asset.url_api.starts_with(DEFAULT_GITHUB_API_BASE_URL)
|| asset.url_api.starts_with(DEFAULT_GITLAB_API_BASE_URL)
|| asset.url_api.starts_with(DEFAULT_FORGEJO_API_BASE_URL)
{
// check if url is reachable, 404 might indicate a private repo or asset.
// This is needed, because private repos and assets cannot be downloaded
// via browser url, therefore a fallback to api_url is needed in such cases.
// Also check Content-Type - if it's text/html, we got a login page (private repo).
true => match HTTP.head(asset.url.clone()).await {
Ok(resp) => {
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if content_type.contains("text/html") {
debug!("Browser URL returned HTML (likely auth page), using API URL");
asset.url_api.clone()
} else {
asset.url.clone()
}
}
Err(_) => asset.url_api.clone(),
},
// Custom API URLs usually imply that a custom GitHub/GitLab instance is used.
// Often times such instances do not allow browser URL downloads, e.g. due to
// upstream company SSOs. Therefore, using the api_url for downloading is the safer approach.
false => {
debug!(
"Since the tool resides on a custom GitHub/GitLab API ({:?}), the asset download will be performed using the given API instead of browser URL download",
asset.url_api
);
asset.url_api.clone()
}
};
let headers = if self.is_gitlab() {
gitlab::get_headers(&url)
} else if self.is_forgejo() {
forgejo::get_headers(&url)
} else {
github::get_headers(&url)
};
ctx.pr.set_message(format!("download {filename}"));
HTTP.download_file_with_headers(url, &file_path, &headers, Some(ctx.pr.as_ref()))
.await?;
// Verify and install
verify_artifact(tv, &file_path, opts, Some(ctx.pr.as_ref()))?;
self.verify_checksum(ctx, tv, &file_path)?;
// Verify attestations or SLSA (check attestations first, fall back to SLSA)
self.verify_attestations_or_slsa(ctx, tv, &file_path)
.await?;
install_artifact(tv, &file_path, opts, Some(ctx.pr.as_ref()))?;
if let Some(bins) = self.get_filter_bins(tv) {
self.create_symlink_bin_dir(tv, bins)?;
}
Ok(())
}
/// Discovers bin paths in the installation directory
fn discover_bin_paths(&self, tv: &ToolVersion) -> Result<Vec<std::path::PathBuf>> {
let opts = tv.request.options();
if let Some(bin_path_template) =
lookup_platform_key(&opts, "bin_path").or_else(|| opts.get("bin_path").cloned())
{
let bin_path = template_string(&bin_path_template, tv);
return Ok(vec![tv.install_path().join(&bin_path)]);
}
let bin_path = tv.install_path().join("bin");
if bin_path.exists() {
return Ok(vec![bin_path]);
}
// Check if the root directory contains an executable file
// If so, use the root directory as a bin path
if let Ok(entries) = std::fs::read_dir(tv.install_path()) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && file::is_executable(&path) {
return Ok(vec![tv.install_path()]);
}
}
}
// Look for bin directory or executables in subdirectories (for extracted archives)
let mut paths = Vec::new();
if let Ok(entries) = std::fs::read_dir(tv.install_path()) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
// Check for {subdir}/bin
let sub_bin_path = path.join("bin");
if sub_bin_path.exists() {
paths.push(sub_bin_path);
} else {
// Check for executables directly in subdir (e.g., tusd_darwin_arm64/tusd)
if let Ok(sub_entries) = std::fs::read_dir(&path) {
for sub_entry in sub_entries.flatten() {
let sub_path = sub_entry.path();
if sub_path.is_file() && file::is_executable(&sub_path) {
paths.push(path.clone());
break;
}
}
}
}
}
}
}
if paths.is_empty() {
Ok(vec![tv.install_path()])
} else {
Ok(paths)
}
}
/// Resolves the asset URL using either explicit patterns or auto-detection.
/// Delegates to resolve_asset_url_for_target with the current platform.
async fn resolve_asset_url(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
) -> Result<ReleaseAsset> {
let current_platform = PlatformTarget::from_current();
self.resolve_asset_url_for_target(tv, opts, repo, api_url, ¤t_platform)
.await
}
/// Resolves asset URL for a specific target platform (for cross-platform lockfile generation)
async fn resolve_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
// Check for direct platform-specific URLs first
if let Some(direct_url) = lookup_platform_key_for_target(opts, "url", target) {
return Ok(ReleaseAsset {
name: get_filename_from_url(&direct_url),
url: direct_url.clone(),
url_api: direct_url.clone(),
digest: None, // Direct URLs don't have API digest
});
}
let version = &tv.version;
let version_prefix = opts.get("version_prefix").map(|s| s.as_str());
if self.is_gitlab() {
try_with_v_prefix(version, version_prefix, |candidate| async move {
self.resolve_gitlab_asset_url_for_target(
tv, opts, repo, api_url, &candidate, target,
)
.await
})
.await
} else if self.is_forgejo() {
try_with_v_prefix(version, version_prefix, |candidate| async move {
self.resolve_forgejo_asset_url_for_target(
tv, opts, repo, api_url, &candidate, target,
)
.await
})
.await
} else {
try_with_v_prefix(version, version_prefix, |candidate| async move {
self.resolve_github_asset_url_for_target(
tv, opts, repo, api_url, &candidate, target,
)
.await
})
.await
}
}
/// Resolves GitHub asset URL for a specific target platform
async fn resolve_github_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
version: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
let release = github::get_release_for_url(api_url, repo, version).await?;
let available_assets: Vec<String> = release.assets.iter().map(|a| a.name.clone()).collect();
// Build asset list with URLs for checksum fetching
let assets_with_urls: Vec<Asset> = release
.assets
.iter()
.map(|a| Asset::new(&a.name, &a.browser_download_url))
.collect();
// Try explicit pattern first
if let Some(pattern) = lookup_platform_key_for_target(opts, "asset_pattern", target)
.or_else(|| opts.get("asset_pattern").cloned())
{
// Template the pattern for the target platform
let templated_pattern = template_string_for_target(&pattern, tv, target);
let asset = release
.assets
.into_iter()
.find(|a| self.matches_pattern(&a.name, &templated_pattern))
.ok_or_else(|| {
eyre::eyre!(
"No matching asset found for pattern: {}\nAvailable assets: {}",
templated_pattern,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = if asset.digest.is_some() {
asset.digest
} else {
self.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await
};
return Ok(ReleaseAsset {
name: asset.name,
url: asset.browser_download_url,
url_api: asset.url,
digest,
});
}
// Fall back to auto-detection for target platform
let asset_name = asset_matcher::detect_asset_for_target(&available_assets, target)?;
let asset = self
.find_asset_case_insensitive(&release.assets, &asset_name, |a| &a.name)
.ok_or_else(|| {
eyre::eyre!(
"Auto-detected asset not found: {}\nAvailable assets: {}",
asset_name,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = if asset.digest.is_some() {
asset.digest.clone()
} else {
self.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await
};
Ok(ReleaseAsset {
name: asset.name.clone(),
url: asset.browser_download_url.clone(),
url_api: asset.url.clone(),
digest,
})
}
/// Resolves GitLab asset URL for a specific target platform
async fn resolve_gitlab_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
version: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
let release = gitlab::get_release_for_url(api_url, repo, version).await?;
let available_assets: Vec<String> = release
.assets
.links
.iter()
.map(|a| a.name.clone())
.collect();
// Build asset list with URLs for checksum fetching
let assets_with_urls: Vec<Asset> = release
.assets
.links
.iter()
.map(|a| Asset::new(&a.name, &a.direct_asset_url))
.collect();
// Try explicit pattern first
if let Some(pattern) = lookup_platform_key_for_target(opts, "asset_pattern", target)
.or_else(|| opts.get("asset_pattern").cloned())
{
// Template the pattern for the target platform
let templated_pattern = template_string_for_target(&pattern, tv, target);
let asset = release
.assets
.links
.into_iter()
.find(|a| self.matches_pattern(&a.name, &templated_pattern))
.ok_or_else(|| {
eyre::eyre!(
"No matching asset found for pattern: {}\nAvailable assets: {}",
templated_pattern,
Self::format_asset_list(available_assets.iter())
)
})?;
// GitLab doesn't provide digests, so try fetching from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
return Ok(ReleaseAsset {
name: asset.name,
url: asset.direct_asset_url.clone(),
url_api: asset.url,
digest,
});
}
// Fall back to auto-detection for target platform
let asset_name = asset_matcher::detect_asset_for_target(&available_assets, target)?;
let asset = self
.find_asset_case_insensitive(&release.assets.links, &asset_name, |a| &a.name)
.ok_or_else(|| {
eyre::eyre!(
"Auto-detected asset not found: {}\nAvailable assets: {}",
asset_name,
Self::format_asset_list(available_assets.iter())
)
})?;
// GitLab doesn't provide digests, so try fetching from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
Ok(ReleaseAsset {
name: asset.name.clone(),
url: asset.direct_asset_url.clone(),
url_api: asset.url.clone(),
digest,
})
}
/// Resolves Forgejo asset URL for a specific target platform
async fn resolve_forgejo_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
version: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
let release = forgejo::get_release_for_url(api_url, repo, version).await?;
let available_assets: Vec<String> = release.assets.iter().map(|a| a.name.clone()).collect();
// Build asset list with URLs for checksum fetching
let assets_with_urls: Vec<Asset> = release
.assets
.iter()
.map(|a| Asset::new(&a.name, &a.browser_download_url))
.collect();
// Helper to build API attachment URL
let asset_url_api = |asset_uuid: &str| {
format!(
"{}/attachments/{}",
api_url.replace("/api/v1", ""),
asset_uuid
)
};
// Try explicit pattern first
if let Some(pattern) = lookup_platform_key_for_target(opts, "asset_pattern", target)
.or_else(|| opts.get("asset_pattern").cloned())
{
// Template the pattern for the target platform
let templated_pattern = template_string_for_target(&pattern, tv, target);
let asset = release
.assets
.into_iter()
.find(|a| self.matches_pattern(&a.name, &templated_pattern))
.ok_or_else(|| {
eyre::eyre!(
"No matching asset found for pattern: {}\nAvailable assets: {}",
templated_pattern,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
return Ok(ReleaseAsset {
name: asset.name,
url: asset.browser_download_url,
url_api: asset_url_api(&asset.uuid),
digest,
});
}
// Fall back to auto-detection for target platform
let asset_name = asset_matcher::detect_asset_for_target(&available_assets, target)?;
let asset = self
.find_asset_case_insensitive(&release.assets, &asset_name, |a| &a.name)
.ok_or_else(|| {
eyre::eyre!(
"Auto-detected asset not found: {}\nAvailable assets: {}",
asset_name,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
Ok(ReleaseAsset {
name: asset.name.clone(),
url: asset.browser_download_url.clone(),
url_api: asset_url_api(&asset.uuid),
digest,
})
}
fn find_asset_case_insensitive<'a, T>(
&self,
assets: &'a [T],
target_name: &str,
get_name: impl Fn(&T) -> &str,
) -> Option<&'a T> {
// First try exact match, then case-insensitive
assets
.iter()
.find(|a| get_name(a) == target_name)
.or_else(|| {
let target_lower = target_name.to_lowercase();
assets
.iter()
.find(|a| get_name(a).to_lowercase() == target_lower)
})
}
fn matches_pattern(&self, asset_name: &str, pattern: &str) -> bool {
// Simple pattern matching - convert glob-like pattern to regex
let regex_pattern = pattern
.replace(".", "\\.")
.replace("*", ".*")
.replace("?", ".");
if let Ok(re) = Regex::new(&format!("^{regex_pattern}$")) {
re.is_match(asset_name)
} else {
// Fallback to simple contains check
asset_name.contains(pattern)
}
}
fn strip_version_prefix(&self, tag_name: &str) -> String {
let opts = self.ba.opts();
// If a custom version_prefix is configured, strip it first
if let Some(prefix) = opts.get("version_prefix")
&& let Some(stripped) = tag_name.strip_prefix(prefix)
{
return stripped.to_string();
}
// Fall back to stripping 'v' prefix
if tag_name.starts_with('v') {
tag_name.trim_start_matches('v').to_string()
} else {
tag_name.to_string()
}
}
/// Tries to fetch a checksum for an asset from release checksum files.
///
/// This method looks for checksum files (SHA256SUMS, *.sha256, etc.) in the release
/// assets and attempts to extract the checksum for the target asset.
///
/// Returns the checksum in "sha256:hash" format if found, None otherwise.
async fn try_fetch_checksum_from_assets(
&self,
assets: &[Asset],
asset_name: &str,
) -> Option<String> {
let fetcher = ChecksumFetcher::new(assets);
match fetcher.fetch_checksum_for(asset_name).await {
Some(result) => {
debug!(
"Found checksum for {} from {}: {}",
asset_name,
result.source_file,
result.to_string_formatted()
);
Some(result.to_string_formatted())
}
None => {
trace!("No checksum file found for {}", asset_name);
None
}
}
}
fn get_filter_bins(&self, tv: &ToolVersion) -> Option<Vec<String>> {
let opts = tv.request.options();
let filter_bins = lookup_platform_key(&opts, "filter_bins")
.or_else(|| opts.get("filter_bins").cloned())?;
Some(
filter_bins
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
)
}
/// Creates a `.mise-bins` directory with symlinks only to the binaries specified in filter_bins.
fn create_symlink_bin_dir(&self, tv: &ToolVersion, bins: Vec<String>) -> Result<()> {
let symlink_dir = tv.install_path().join(".mise-bins");
file::create_dir_all(&symlink_dir)?;
// Find where the actual binaries are
let install_path = tv.install_path();
let bin_paths = self.discover_bin_paths(tv)?;
// Collect all possible source directories (install root + discovered bin paths)
let mut src_dirs = bin_paths;
if !src_dirs.contains(&install_path) {
src_dirs.push(install_path);
}
for bin_name in bins {
// Find the binary in any of the source directories
let mut found = false;
for dir in &src_dirs {
let src = dir.join(&bin_name);
if src.exists() {
let dst = symlink_dir.join(&bin_name);
if !dst.exists() {
file::make_symlink_or_copy(&src, &dst)?;
}
found = true;
break;
}
}
if !found {
warn!(
"Could not find binary '{}' in install directories. Available paths: {:?}",
bin_name, src_dirs
);
}
}
Ok(())
}
/// Verify artifact using GitHub attestations or SLSA provenance.
/// Tries attestations first, falls back to SLSA if no attestations found.
/// If verification is attempted and fails, it's a hard error.