easy-install 1.3.10

easy-install
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
use crate::artifact::GhArtifacts;
use crate::error::{Context, Result, err};
use crate::tool::parse_and_validate_url;
use crate::{manfiest::DistManifest, tool::is_url};
use easy_archive::{File, Fmt};
use regex::Regex;
use reqwest::Client;
use reqwest::header::{HeaderMap, HeaderValue};
use serde::de::DeserializeOwned;
use std::sync::{LazyLock, OnceLock};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::time::{sleep, timeout};
use tracing::{trace, warn};

// Credential cache for GitHub token detection
static GITHUB_TOKEN_CACHE: OnceLock<Option<String>> = OnceLock::new();

// Matches GitHub release asset download URLs so that private-repo downloads
// can be retried through the API:
// https://github.com/{owner}/{repo}/releases/download/{tag}/{filename}
static RE_GH_RELEASE_DOWNLOAD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^https://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)/releases/download/(?P<tag>[^/]+)/(?P<filename>.+)$",
    )
    .unwrap()
});

async fn retry_request<F, Fut, T>(
    max_retries: usize,
    operation: F,
    operation_name: &str,
) -> Result<T>
where
    F: Fn() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let mut last_error = None;

    for attempt in 0..=max_retries {
        match operation().await {
            Ok(result) => {
                if attempt > 0 {
                    trace!(
                        "{} succeeded on attempt {}/{}",
                        operation_name,
                        attempt + 1,
                        max_retries + 1
                    );
                }
                return Ok(result);
            }
            Err(e) => {
                last_error = Some(e);
                if attempt < max_retries {
                    let delay = Duration::from_millis(100 * 2_u64.pow(attempt as u32));
                    trace!(
                        "{} failed on attempt {}/{}, retrying in {:?}...",
                        operation_name,
                        attempt + 1,
                        max_retries + 1,
                        delay
                    );
                    sleep(delay).await;
                } else {
                    trace!(
                        "{} failed after {} attempts",
                        operation_name,
                        max_retries + 1
                    );
                }
            }
        }
    }

    Err(last_error.unwrap_or_else(|| err!("retry_request: no error captured")))
}

async fn detect_github_token() -> Option<String> {
    // Check cache first
    if let Some(cached) = GITHUB_TOKEN_CACHE.get() {
        return cached.clone();
    }

    // Check GITHUB_TOKEN env var first — it's the most reliable and
    // fastest method in CI runners (no subprocess overhead).
    let token = if let Ok(t) = std::env::var("GITHUB_TOKEN")
        && !t.is_empty()
    {
        Some(t)
    } else if let Some(t) = try_github_cli_token().await {
        Some(t)
    } else { try_git_credential_manager().await };

    // Cache the result (even if None)
    let _ = GITHUB_TOKEN_CACHE.set(token.clone());

    token
}

async fn try_github_cli_token() -> Option<String> {
    trace!("Attempting to detect GitHub CLI token");

    let timeout_duration = Duration::from_secs(5);

    // Platform-specific command execution
    #[cfg(target_os = "windows")]
    let mut cmd = {
        let mut c = Command::new("powershell");
        c.args(["-c", "gh auth token"]);
        c
    };

    #[cfg(not(target_os = "windows"))]
    let mut cmd = {
        let mut c = Command::new("gh");
        c.arg("auth").arg("token");
        c
    };

    // Execute command with timeout
    let result = timeout(timeout_duration, cmd.output()).await;

    match result {
        Ok(Ok(output)) if output.status.success() => {
            let token = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !token.is_empty() {
                trace!("Successfully detected GitHub CLI token");
                return Some(token);
            }
            trace!("GitHub CLI returned empty token");
            None
        }
        Ok(Ok(output)) => {
            trace!("GitHub CLI command failed with status: {}", output.status);
            None
        }
        Ok(Err(e)) => {
            trace!("Failed to execute GitHub CLI command: {}", e);
            None
        }
        Err(_) => {
            warn!("GitHub CLI token detection timed out after 5 seconds");
            None
        }
    }
}

struct GitCredentialOutput {
    protocol: Option<String>,
    host: Option<String>,
    username: Option<String>,
    password: Option<String>,
}

impl GitCredentialOutput {
    fn parse(output: &str) -> Self {
        let mut result = GitCredentialOutput {
            protocol: None,
            host: None,
            username: None,
            password: None,
        };

        for line in output.lines() {
            if let Some((key, value)) = line.split_once('=') {
                match key {
                    "protocol" => result.protocol = Some(value.to_string()),
                    "host" => result.host = Some(value.to_string()),
                    "username" => result.username = Some(value.to_string()),
                    "password" => result.password = Some(value.to_string()),
                    _ => {}
                }
            }
        }

        result
    }

    fn get_token(&self) -> Option<String> {
        self.password.clone()
    }
}

async fn try_git_credential_manager() -> Option<String> {
    trace!("Attempting to detect Git Credential Manager token");

    let timeout_duration = Duration::from_secs(5);

    let mut cmd = Command::new("git");
    cmd.args(["credential", "fill"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .env("GIT_TERMINAL_PROMPT", "0");

    // Spawn the process
    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            trace!("Failed to spawn git credential fill command: {}", e);
            return None;
        }
    };

    // Write input to stdin
    if let Some(mut stdin) = child.stdin.take() {
        let input = "protocol=https\nhost=github.com\n\n";
        if let Err(e) = timeout(timeout_duration, stdin.write_all(input.as_bytes())).await {
            trace!("Failed to write to git credential stdin: {}", e);
            let _ = child.kill().await;
            return None;
        }
    } else {
        trace!("Failed to get stdin for git credential command");
        let _ = child.kill().await;
        return None;
    }

    // Wait for output with timeout
    let result = timeout(timeout_duration, child.wait_with_output()).await;

    match result {
        Ok(Ok(output)) if output.status.success() => {
            let output_str = String::from_utf8_lossy(&output.stdout);
            let parsed = GitCredentialOutput::parse(&output_str);

            if let Some(token) = parsed.get_token()
                && !token.is_empty()
            {
                trace!("Successfully detected Git Credential Manager token");
                return Some(token);
            }
            trace!("Git Credential Manager returned no password");
            None
        }
        Ok(Ok(output)) => {
            trace!(
                "Git credential command failed with status: {}",
                output.status
            );
            None
        }
        Ok(Err(e)) => {
            trace!("Failed to execute git credential command: {}", e);
            None
        }
        Err(_) => {
            warn!("Git Credential Manager detection timed out after 5 seconds");
            None
        }
    }
}

fn is_github_url(parsed: &reqwest::Url) -> bool {
    if let Some(host) = parsed.host_str() {
        return host == "github.com"
            || host.ends_with(".github.com")
            || host == "githubusercontent.com"
            || host.ends_with(".githubusercontent.com");
    }
    false
}

async fn get_headers(parsed: &reqwest::Url) -> Result<HeaderMap> {
    let mut headers = HeaderMap::new();
    headers.append("User-Agent", HeaderValue::from_static("reqwest"));

    // Only add GitHub token for GitHub URLs to prevent token leakage
    if is_github_url(parsed) {
        if let Some(token) = detect_github_token().await {
            headers.append(
                "Authorization",
                HeaderValue::from_str(&format!("Bearer {}", token))
                    .context("Authorization token error")?,
            );
            trace!("Using detected GitHub token for authentication");
        } else {
            trace!("No GitHub token detected, proceeding without authentication");
        }
    }

    Ok(headers)
}

fn create_client() -> &'static Client {
    static CLIENT: OnceLock<Client> = OnceLock::new();
    CLIENT.get_or_init(|| {
        reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(30))
            .cookie_store(true)
            .build()
            .expect("Failed to create HTTP client")
    })
}

/// `browser_download_url` is a GitHub *web* endpoint: for private repos it
/// does not accept API tokens (GitHub returns 404 to avoid leaking the
/// repo's existence), which is why the asset list can be fetched from the
/// API but the download itself fails. The supported way to download a
/// private release asset is the asset API endpoint with
/// `Accept: application/octet-stream`, which 302s to a pre-signed CDN URL.
async fn download_private_release_asset(
    parsed: &reqwest::Url,
    timeout_dur: Duration,
) -> Result<Option<reqwest::Response>> {
    let Some(captures) = RE_GH_RELEASE_DOWNLOAD.captures(parsed.as_str()) else {
        return Ok(None);
    };
    let (Some(owner), Some(repo), Some(tag), Some(filename)) = (
        captures.name("owner"),
        captures.name("repo"),
        captures.name("tag"),
        captures.name("filename"),
    ) else {
        return Ok(None);
    };
    // Without a token there is no way to authenticate the API request.
    if detect_github_token().await.is_none() {
        return Ok(None);
    }

    trace!("download_private_release_asset {}", parsed.as_str());
    let client = create_client();

    // Resolve the asset's API URL by matching the filename in the release.
    let release_api = format!(
        "https://api.github.com/repos/{}/{}/releases/tags/{}",
        owner.as_str(),
        repo.as_str(),
        tag.as_str()
    );
    let api_parsed = parse_and_validate_url(&release_api)?;
    let response = client
        .get(api_parsed.clone())
        .timeout(timeout_dur)
        .headers(get_headers(&api_parsed).await?)
        .send()
        .await
        .context("release api send failed")?;
    if response.status() != reqwest::StatusCode::OK {
        trace!("release api returned status: {}", response.status());
        return Ok(None);
    }
    let release: GhArtifacts = response.json().await.context("release api json failed")?;
    let Some(asset) = release
        .assets
        .iter()
        .find(|a| a.name == filename.as_str() || a.browser_download_url == parsed.as_str())
    else {
        trace!(
            "asset {} not found in release {}",
            filename.as_str(),
            tag.as_str()
        );
        return Ok(None);
    };

    // The octet-stream Accept header makes the API return the binary
    // (via a 302 to a pre-signed URL) instead of the asset metadata JSON.
    let Some(api_url) = &asset.url else {
        trace!("asset {} has no API url", filename.as_str());
        return Ok(None);
    };
    let asset_parsed = parse_and_validate_url(api_url)?;
    let mut headers = get_headers(&asset_parsed).await?;
    headers.append(
        "Accept",
        HeaderValue::from_static("application/octet-stream"),
    );
    let response = client
        .get(asset_parsed)
        .timeout(timeout_dur)
        .headers(headers)
        .send()
        .await
        .context("asset api send failed")?;
    if response.status() != reqwest::StatusCode::OK {
        trace!("asset api returned status: {}", response.status());
        return Ok(None);
    }
    Ok(Some(response))
}

pub(crate) async fn download_json<T: DeserializeOwned>(
    url: &str,
    retry: usize,
    timeout: u64,
) -> Result<T> {
    let parsed = parse_and_validate_url(url)?;
    let timeout_dur = Duration::from_secs(timeout);

    retry_request(
        retry,
        || async {
            let client = create_client();
            let response = match client
                .get(parsed.clone())
                .timeout(timeout_dur)
                .headers(get_headers(&parsed).await?)
                .send()
                .await
            {
                Ok(resp) => resp,
                Err(e) => {
                    if e.is_timeout() {
                        return Err(err!(
                            "Request timed out after {} seconds: {}",
                            timeout,
                            url
                        ));
                    }
                    return Err(e).context("send failed");
                }
            };
            if response.status() != reqwest::StatusCode::OK {
                return Err(err!(
                    "request failed with status: {}",
                    response.status()
                ));
            }
            response.json::<T>().await.context("json parse failed")
        },
        &format!("download_json({})", url),
    )
    .await
}

pub(crate) async fn get_bytes(url: &str, retry: usize, timeout: u64) -> Result<Vec<u8>> {
    let bin = if is_url(url) {
        download_binary(url, retry, timeout).await?
    } else {
        std::fs::read(url).context("read file failed")?.to_vec()
    };
    Ok(bin)
}

pub(crate) fn extract_bytes(bytes: Vec<u8>, fmt: Fmt) -> Result<Vec<File>> {
    let files = fmt
        .decode(bytes)?
        .into_iter()
        // FIXME: remove __MACOSX
        .filter(|i| !i.path.starts_with("__MACOSX"))
        .collect();

    Ok(files)
}

pub(crate) async fn download(url: &str, retry: usize, timeout: u64) -> Result<reqwest::Response> {
    let parsed = parse_and_validate_url(url)?;
    let timeout_dur = Duration::from_secs(timeout);

    retry_request(
        retry,
        || async {
            trace!("download {}", url);
            let client = create_client();
            let headers = get_headers(&parsed).await?;
            let response = match client
                .get(parsed.clone())
                .timeout(timeout_dur)
                .headers(headers)
                .send()
                .await
            {
                Ok(resp) => resp,
                Err(e) => {
                    if e.is_timeout() {
                        return Err(err!(
                            "Request timed out after {} seconds: {}",
                            timeout,
                            url
                        ));
                    }
                    return Err(e).context("send failed");
                }
            };
            if response.status() != reqwest::StatusCode::OK {
                let status = response.status();
                // Private release assets: browser_download_url rejects API
                // tokens, so retry through the GitHub asset API instead.
                if matches!(
                    status,
                    reqwest::StatusCode::UNAUTHORIZED
                        | reqwest::StatusCode::FORBIDDEN
                        | reqwest::StatusCode::NOT_FOUND
                ) && let Some(resp) =
                    download_private_release_asset(&parsed, timeout_dur).await?
                {
                    return Ok(resp);
                }
                return Err(err!("request failed with status: {}", status));
            }
            Ok(response)
        },
        &format!("download({})", url),
    )
    .await
}

pub(crate) async fn download_dist_manfiest(
    url: &str,
    retry: usize,
    timeout: u64,
) -> Result<DistManifest> {
    let url_clone = url.to_string();
    retry_request(
        retry,
        || async {
            trace!("download_dist_manfiest {}", url_clone);
            let response = download(&url_clone, 0, timeout).await?;
            response.json().await.context("json parse failed")
        },
        &format!("download_dist_manfiest({})", url),
    )
    .await
}

pub(crate) async fn download_binary(url: &str, retry: usize, timeout: u64) -> Result<Vec<u8>> {
    let url_clone = url.to_string();
    retry_request(
        retry,
        || async {
            trace!("download_binary {}", url_clone);
            let response = download(&url_clone, 0, timeout).await?;
            let bytes = response.bytes().await.context("bytes failed")?;
            Ok(bytes.to_vec())
        },
        &format!("download_binary({})", url),
    )
    .await
}

pub(crate) fn read_dist_manfiest(url: &str) -> Result<DistManifest> {
    trace!("read_dist_manfiest {}", url);
    let s = std::fs::read_to_string(url).context(format!("read file error: {url}"))?;
    serde_json::from_str(&s).context("json parse failed")
}

#[cfg(test)]
mod test {
    use easy_archive::Fmt;

    use crate::download::{extract_bytes, get_bytes};

    #[tokio::test]
    async fn test_download() {
        let url = "https://github.com/ahaoboy/mujs-build/releases/download/v0.0.1/mujs-x86_64-unknown-linux-gnu.tar.gz";
        let bytes = get_bytes(url, 3, 30).await.expect("donwload error");
        let fmt = Fmt::guess(url).expect("fmt error");
        let files = extract_bytes(bytes, fmt).expect("extract_bytes failed");
        assert!(files.iter().any(|i| i.path == "mujs"));
        assert!(files.iter().any(|i| i.path == "mujs-pp"));
        assert!(files.iter().any(|i| i.path == "libmujs.a"));
    }
}