cora-code 0.18.0

CLI-first AI code review — BYOK, diff/scan/branch, pre-commit hooks
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
//! `cora upgrade` — check for updates and self-upgrade.
//!
//! Detects OS/arch, fetches latest release from GitHub, downloads,
//! verifies checksum, replaces the running binary.
//!
//! Uses a blocking tokio runtime for the HTTP calls (reqwest is async-only
//! in cora-code, unlike uteke which uses reqwest::blocking).

use std::fs;
use std::io::{self, BufRead, Write};
use std::path::PathBuf;

use colored::Colorize;
use sha2::{Digest, Sha256};

const REPO: &str = "codecoradev/cora-code";
const BINARY_NAME: &str = "cora";

/// Maximum accepted size for a release archive (compressed).
const MAX_ARCHIVE_BYTES: u64 = 256 * 1024 * 1024;
/// Maximum accepted size for the checksums file / API JSON.
const MAX_SMALL_BYTES: u64 = 1024 * 1024;
/// Maximum accepted size for the extracted binary.
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
/// OIDC issuer that must appear in the signing certificate (GitHub Actions).
const COSIGN_OIDC_ISSUER: &str = "https://token.actions.githubusercontent.com";
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);

/// Entry point for `cora upgrade`.
///
/// `check_only` = true corresponds to `cora upgrade --check`:
/// only print whether an update is available, do not download.
pub async fn run(yes: bool, check_only: bool) -> anyhow::Result<i32> {
    let current_version = env!("CARGO_PKG_VERSION");
    println!("{} Current version: {current_version}", "[INFO]".green());

    // Detect current binary path
    let current_exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!(
                "{} Cannot determine current binary path: {e}",
                "[ERROR]".red()
            );
            eprintln!("        If installed via cargo, run: cargo install --path .");
            return Ok(1);
        }
    };

    // Detect OS and architecture
    let os = detect_os();
    let arch = detect_arch();

    // Get latest release version
    let latest_version = match get_latest_version().await {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{} {e}", "[ERROR]".red());
            return Ok(1);
        }
    };

    // Normalize: strip leading 'v' from GitHub tag for comparison
    let latest_clean = latest_version.trim_start_matches('v');

    // Check if already up to date
    if latest_clean == current_version {
        println!(
            "{} Already up to date ({current_version})",
            "[INFO]".green()
        );
        return Ok(0);
    }

    println!("{} Latest version:  {latest_version}", "[INFO]".cyan());
    println!(
        "{} Release notes:  https://github.com/{REPO}/releases/tag/{latest_version}",
        "[INFO]".dimmed()
    );

    if check_only {
        return Ok(0);
    }

    // Confirm (unless --yes)
    if !yes {
        print!("? Update to {latest_version}? [y/N] ");
        io::stdout()
            .flush()
            .map_err(|e| anyhow::anyhow!("stdout flush: {e}"))?;
        let mut input = String::new();
        io::stdin()
            .lock()
            .read_line(&mut input)
            .map_err(|e| anyhow::anyhow!("stdin read: {e}"))?;
        let input = input.trim().to_lowercase();
        if input != "y" && input != "yes" {
            println!("{} Update cancelled.", "[INFO]".dimmed());
            return Ok(0);
        }
    }

    // Build target and download
    let target = match get_target(&os, &arch) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("{} {e}", "[ERROR]".red());
            return Ok(1);
        }
    };

    let archive_name = format!("{BINARY_NAME}-{target}-{latest_version}.tar.gz");
    let download_url =
        format!("https://github.com/{REPO}/releases/download/{latest_version}/{archive_name}");

    println!("{} Downloading {archive_name} ...", "[INFO]".green());

    // Random, 0700 temp dir (removed on drop, including early returns).
    let temp_guard =
        tempfile::tempdir().map_err(|e| anyhow::anyhow!("Failed to create temp dir: {e}"))?;
    let temp_dir = temp_guard.path().to_path_buf();
    let archive_path = temp_dir.join(&archive_name);

    // Download using a blocking tokio runtime (reqwest is async-only)
    let archive_bytes = match download_async(&download_url, MAX_ARCHIVE_BYTES).await {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{} Download failed: {e}", "[ERROR]".red());
            return Ok(1);
        }
    };

    fs::write(&archive_path, &archive_bytes)
        .map_err(|e| anyhow::anyhow!("Failed to write archive: {e}"))?;

    // Verify checksum
    let checksums_url = format!(
        "https://github.com/{REPO}/releases/download/{latest_version}/checksums-sha256.txt"
    );

    println!("{} Verifying checksum ...", "[INFO]".green());

    let skip_checksum = match skip_checksum_decision(
        std::env::var("CORA_UPGRADE_SKIP_CHECKSUM").ok().as_deref(),
        std::env::var("CORA_UPGRADE_I_UNDERSTAND").ok().as_deref(),
    ) {
        Ok(v) => v,
        Err(msg) => {
            eprintln!("{} {msg}", "[ERROR]".red());
            return Ok(1);
        }
    };

    let require_sig =
        match parse_require_signature(std::env::var("CORA_REQUIRE_SIGNATURE").ok().as_deref()) {
            Ok(v) => v,
            Err(msg) => {
                eprintln!("{} {msg}", "[ERROR]".red());
                return Ok(1);
            }
        };
    if skip_checksum && require_sig {
        eprintln!(
            "{} CORA_UPGRADE_SKIP_CHECKSUM conflicts with CORA_REQUIRE_SIGNATURE=1 (the signature covers the checksums file). Unset one.",
            "[ERROR]".red()
        );
        return Ok(1);
    }

    if skip_checksum {
        eprintln!(
            "{} !!! CHECKSUM VERIFICATION DISABLED (CORA_UPGRADE_SKIP_CHECKSUM + CORA_UPGRADE_I_UNDERSTAND) !!!",
            "[WARN]".yellow().bold()
        );
        eprintln!(
            "{} The downloaded binary is NOT verified and will replace the running one.",
            "[WARN]".yellow().bold()
        );
    } else {
        let checksums_bytes = match download_async(&checksums_url, MAX_SMALL_BYTES).await {
            Ok(b) => b,
            Err(e) => {
                eprintln!("{} Failed to download checksums: {e}", "[ERROR]".red());
                eprintln!(
                    "        (Unsafe bypass: CORA_UPGRADE_SKIP_CHECKSUM=1 CORA_UPGRADE_I_UNDERSTAND=1)"
                );
                return Ok(1);
            }
        };

        let checksums_text = String::from_utf8_lossy(&checksums_bytes).to_string();

        // Keyless cosign signature over the checksums file (#591).
        let checksums_path = temp_dir.join("checksums-sha256.txt");
        fs::write(&checksums_path, &checksums_bytes)
            .map_err(|e| anyhow::anyhow!("Failed to write checksums: {e}"))?;
        let bundle_state =
            match download_optional_async(&bundle_url(&latest_version), MAX_SMALL_BYTES).await {
                Ok(Some(b)) => BundleState::Present(b),
                Ok(None) => BundleState::Absent,
                Err(e) => BundleState::Error(e.to_string()),
            };
        match verify_signature_policy(
            require_sig,
            bundle_state,
            &SystemCosign,
            &temp_dir,
            &checksums_path,
        ) {
            Ok(SigOutcome::Verified) => {
                println!("{} Signature verified (cosign keyless)", "[INFO]".green())
            }
            Ok(SigOutcome::Unverified(note)) => eprintln!("{} {note}", "[WARN]".yellow()),
            Err(msg) => {
                eprintln!("{} {msg}", "[ERROR]".red());
                return Ok(1);
            }
        }

        let expected = match parse_checksum(&checksums_text, &archive_name) {
            Some(h) => h,
            None => {
                eprintln!(
                    "{} Checksum for '{archive_name}' not found in checksums file.",
                    "[ERROR]".red()
                );
                eprintln!(
                    "        (Unsafe bypass: CORA_UPGRADE_SKIP_CHECKSUM=1 CORA_UPGRADE_I_UNDERSTAND=1)"
                );
                return Ok(1);
            }
        };

        let actual = sha256_file(&archive_path)?;
        if actual != expected {
            eprintln!(
                "{} Checksum mismatch! Expected: {expected}, got: {actual}",
                "[ERROR]".red()
            );
            return Ok(1);
        }
        println!("{} Checksum verified: {actual}", "[INFO]".green());
    }

    // Extract only the single regular-file binary entry; reject links.
    println!("{} Extracting ...", "[INFO]".green());
    let extracted_binary = match extract_binary(&archive_path, &temp_dir) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{} {e}", "[ERROR]".red());
            return Ok(1);
        }
    };

    let install_dir = current_exe
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine install directory"))?;

    // Copy to temp file first, then rename (atomic on POSIX)
    let temp_new = install_dir.join(format!("{BINARY_NAME}.new"));
    fs::copy(&extracted_binary, &temp_new)
        .map_err(|e| anyhow::anyhow!("Failed to copy new binary: {e}"))?;

    // Verify the new binary runs
    match std::process::Command::new(&temp_new)
        .arg("--version")
        .output()
    {
        Ok(output) if output.status.success() => {
            let new_version = String::from_utf8_lossy(&output.stdout).trim().to_string();
            let extracted_version = new_version.split_whitespace().nth(1).unwrap_or("unknown");
            println!(
                "{} Verified new binary: {extracted_version}",
                "[INFO]".green()
            );
        }
        Ok(output) => {
            let _ = fs::remove_file(&temp_new);
            eprintln!(
                "{} New binary failed to run: {}",
                "[ERROR]".red(),
                String::from_utf8_lossy(&output.stderr)
            );
            return Ok(1);
        }
        Err(e) => {
            let _ = fs::remove_file(&temp_new);
            eprintln!("{} Failed to verify new binary: {e}", "[ERROR]".red());
            return Ok(1);
        }
    }

    // Atomic rename
    fs::rename(&temp_new, &current_exe)
        .map_err(|e| anyhow::anyhow!("Failed to replace binary: {e}"))?;

    // Cleanup

    println!(
        "{} Update complete. ({current_version} → {latest_version})",
        "[INFO]".green().bold()
    );

    Ok(0)
}

fn http_client(follow_redirects: bool) -> anyhow::Result<reqwest::Client> {
    let mut b = reqwest::Client::builder()
        .connect_timeout(CONNECT_TIMEOUT)
        .timeout(REQUEST_TIMEOUT)
        .user_agent("cora-upgrade");
    if !follow_redirects {
        b = b.redirect(reqwest::redirect::Policy::none());
    }
    b.build()
        .map_err(|e| anyhow::anyhow!("Failed to build HTTP client: {e}"))
}

/// Download a URL with timeouts and a hard cap on the body size.
async fn download_async(url: &str, max_bytes: u64) -> anyhow::Result<Vec<u8>> {
    download_optional_async(url, max_bytes)
        .await?
        .ok_or_else(|| anyhow::anyhow!("HTTP 404 Not Found"))
}

/// Like [`download_async`] but maps HTTP 404 to `Ok(None)`.
async fn download_optional_async(url: &str, max_bytes: u64) -> anyhow::Result<Option<Vec<u8>>> {
    let mut resp = http_client(true)?
        .get(url)
        .send()
        .await
        .map_err(|e| anyhow::anyhow!("HTTP request failed: {e}"))?;

    if resp.status() == reqwest::StatusCode::NOT_FOUND {
        return Ok(None);
    }
    if !resp.status().is_success() {
        anyhow::bail!("HTTP {}", resp.status());
    }
    if let Some(len) = resp.content_length() {
        if len > max_bytes {
            anyhow::bail!("Response too large ({len} bytes, limit {max_bytes})");
        }
    }

    let mut buf: Vec<u8> = Vec::new();
    while let Some(chunk) = resp
        .chunk()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to read response body: {e}"))?
    {
        if buf.len() as u64 + chunk.len() as u64 > max_bytes {
            anyhow::bail!("Response exceeded size limit of {max_bytes} bytes");
        }
        buf.extend_from_slice(&chunk);
    }
    Ok(Some(buf))
}

/// URL of the cosign bundle published next to the checksums file.
fn bundle_url(tag: &str) -> String {
    format!("https://github.com/{REPO}/releases/download/{tag}/checksums-sha256.txt.sigstore.json")
}

/// Regexp the signing certificate identity must match: the release workflow of
/// this repository, run from a `v*` tag. (`.` is escaped so only the real file matches.)
fn cosign_identity_regexp() -> String {
    format!("^https://github.com/{REPO}/\\.github/workflows/release\\.yml@refs/tags/v")
}

/// Parse `CORA_REQUIRE_SIGNATURE`. Unknown values are an error, never a silent "off".
fn parse_require_signature(v: Option<&str>) -> Result<bool, String> {
    match v {
        None | Some("") | Some("0") | Some("false") => Ok(false),
        Some("1") | Some("true") => Ok(true),
        Some(o) => Err(format!("CORA_REQUIRE_SIGNATURE must be 1 or 0 (got '{o}')")),
    }
}

/// Result of fetching the signature bundle.
enum BundleState {
    Present(Vec<u8>),
    /// HTTP 404: release predates signing.
    Absent,
    Error(String),
}

#[derive(Debug, PartialEq, Eq)]
enum SigOutcome {
    Verified,
    /// Proceeding on checksum-only; the string is the notice to show.
    Unverified(String),
}

/// Seam over the external `cosign` binary so the policy is unit-testable.
trait CosignRunner {
    fn available(&self) -> bool;
    fn verify(&self, bundle: &std::path::Path, blob: &std::path::Path) -> Result<(), String>;
}

struct SystemCosign;

impl CosignRunner for SystemCosign {
    fn available(&self) -> bool {
        std::process::Command::new("cosign")
            .arg("version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok()
    }

    fn verify(&self, bundle: &std::path::Path, blob: &std::path::Path) -> Result<(), String> {
        let out = std::process::Command::new("cosign")
            .arg("verify-blob")
            .arg("--bundle")
            .arg(bundle)
            .arg("--certificate-identity-regexp")
            .arg(cosign_identity_regexp())
            .arg("--certificate-oidc-issuer")
            .arg(COSIGN_OIDC_ISSUER)
            .arg(blob)
            .output()
            .map_err(|e| format!("failed to run cosign: {e}"))?;
        if out.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

const COSIGN_INSTALL_HINT: &str = "https://docs.sigstore.dev/cosign/system_config/installation/";

/// Signature policy (same as install.sh):
/// bundle + cosign => verify, failure fatal; cosign missing or bundle absent =>
/// notice, fatal when `require`; any other bundle fetch error => fatal.
fn verify_signature_policy(
    require: bool,
    bundle: BundleState,
    runner: &dyn CosignRunner,
    dir: &std::path::Path,
    checksums_path: &std::path::Path,
) -> Result<SigOutcome, String> {
    let bytes = match bundle {
        BundleState::Present(b) => b,
        BundleState::Absent if require => {
            return Err(
                "No signature bundle published for this release but CORA_REQUIRE_SIGNATURE=1. Refusing to upgrade."
                    .into(),
            )
        }
        BundleState::Absent => {
            return Ok(SigOutcome::Unverified(
                "No cosign signature published for this release; verified by SHA-256 checksum only."
                    .into(),
            ))
        }
        BundleState::Error(e) => {
            return Err(format!(
                "Failed to download signature bundle: {e}. Refusing to upgrade."
            ))
        }
    };
    if !runner.available() {
        if require {
            return Err(format!(
                "cosign not found but CORA_REQUIRE_SIGNATURE=1. Install cosign: {COSIGN_INSTALL_HINT}"
            ));
        }
        return Ok(SigOutcome::Unverified(format!(
            "Signature NOT verified (checksum-only): cosign not found. Install it to verify: {COSIGN_INSTALL_HINT}"
        )));
    }
    let bundle_path = dir.join("checksums-sha256.txt.sigstore.json");
    fs::write(&bundle_path, bytes).map_err(|e| format!("Failed to write bundle: {e}"))?;
    runner
        .verify(&bundle_path, checksums_path)
        .map(|()| SigOutcome::Verified)
        .map_err(|e| format!("cosign signature verification FAILED: {e}. Refusing to upgrade."))
}

/// Decide whether checksum verification may be skipped.
///
/// Requires BOTH `CORA_UPGRADE_SKIP_CHECKSUM` (1/true) and the explicit
/// acknowledgement `CORA_UPGRADE_I_UNDERSTAND` (1/true). The skip variable
/// alone is an error rather than a silent downgrade.
fn skip_checksum_decision(skip: Option<&str>, ack: Option<&str>) -> Result<bool, String> {
    let on = |v: Option<&str>| matches!(v, Some("1") | Some("true"));
    if !on(skip) {
        return Ok(false);
    }
    if on(ack) {
        Ok(true)
    } else {
        Err("CORA_UPGRADE_SKIP_CHECKSUM is set but unsafe skipping also requires              CORA_UPGRADE_I_UNDERSTAND=1. Refusing to continue."
            .to_string())
    }
}

/// A release tag must look like `vX.Y.Z[-suffix]` (safe chars only) since it is
/// interpolated into download URLs.
fn is_valid_tag(tag: &str) -> bool {
    tag.len() <= 64
        && tag.starts_with('v')
        && tag.len() > 1
        && tag
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'))
}

/// Extract only the top-level `cora` regular file from the tarball into `dest_dir`.
///
/// Any symlink/hardlink entry anywhere in the archive causes the whole archive
/// to be rejected, as do unsafe paths.
fn extract_binary(
    archive_path: &std::path::Path,
    dest_dir: &std::path::Path,
) -> anyhow::Result<PathBuf> {
    let file =
        fs::File::open(archive_path).map_err(|e| anyhow::anyhow!("Failed to open archive: {e}"))?;
    let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file));
    let dest = dest_dir.join(BINARY_NAME);
    let mut found = false;

    for entry in archive
        .entries()
        .map_err(|e| anyhow::anyhow!("Failed to read archive entries: {e}"))?
    {
        let mut entry = entry.map_err(|e| anyhow::anyhow!("Failed to read archive entry: {e}"))?;
        let ty = entry.header().entry_type();
        let path = entry
            .path()
            .map_err(|e| anyhow::anyhow!("Archive path error: {e}"))?
            .into_owned();
        let path_str = path.to_string_lossy().to_string();

        if path_str.starts_with('/')
            || path
                .components()
                .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            anyhow::bail!("Archive contains unsafe paths - refusing to extract");
        }
        if ty.is_symlink() || ty.is_hard_link() {
            anyhow::bail!(
                "Archive contains a symlink/hardlink entry ('{path_str}') - refusing to extract"
            );
        }
        if path_str.trim_start_matches("./") == BINARY_NAME {
            if !ty.is_file() {
                anyhow::bail!("Archive entry '{BINARY_NAME}' is not a regular file");
            }
            if found {
                anyhow::bail!("Archive contains duplicate '{BINARY_NAME}' entries");
            }
            if entry.size() > MAX_BINARY_BYTES {
                anyhow::bail!("Binary in archive is too large ({} bytes)", entry.size());
            }
            entry
                .unpack(&dest)
                .map_err(|e| anyhow::anyhow!("Failed to extract binary: {e}"))?;
            found = true;
        }
    }

    if !found {
        anyhow::bail!("Binary '{BINARY_NAME}' not found in archive");
    }
    Ok(dest)
}

fn detect_os() -> String {
    match std::env::consts::OS {
        "linux" => "linux".to_string(),
        "macos" => "darwin".to_string(),
        os => os.to_string(),
    }
}

fn detect_arch() -> String {
    match std::env::consts::ARCH {
        "x86_64" => "x86_64".to_string(),
        "aarch64" => "aarch64".to_string(),
        arch => arch.to_string(),
    }
}

fn get_target(os: &str, arch: &str) -> Result<String, String> {
    match (os, arch) {
        ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu".into()),
        ("linux", "aarch64") => Ok("aarch64-unknown-linux-gnu".into()),
        ("darwin", "aarch64") => Ok("aarch64-apple-darwin".into()),
        ("darwin", "x86_64") => Ok("x86_64-apple-darwin".into()),
        _ => Err(format!("Unsupported platform: {os} {arch}")),
    }
}

/// Get latest release tag from GitHub.
///
/// Primary: parse 302 redirect (no API call, no rate limit).
/// Fallback: GitHub REST API.
async fn get_latest_version() -> Result<String, String> {
    let probe = http_client(false).map_err(|e| e.to_string())?;
    let client = http_client(true).map_err(|e| e.to_string())?;

    // Primary: HEAD request, parse Location header redirect (not followed)
    let resp = probe
        .head(format!("https://github.com/{REPO}/releases/latest"))
        .send()
        .await
        .map_err(|e| format!("Failed to check latest release: {e}"))?;

    if let Some(location) = resp.headers().get("location") {
        let loc = location.to_str().unwrap_or_default();
        // Redirect URL: https://github.com/codecoradev/cora-code/releases/tag/v0.14.0
        if let Some(tag) = loc.rsplit('/').next() {
            let tag = tag.trim_end_matches('?');
            if is_valid_tag(tag) {
                return Ok(tag.to_string());
            }
        }
    }

    // Fallback: GitHub API
    let api_url = format!("https://api.github.com/repos/{REPO}/releases/latest");
    let resp = client
        .get(&api_url)
        .send()
        .await
        .map_err(|e| format!("GitHub API failed: {e}"))?;

    if resp.status().is_success() {
        if resp.content_length().is_some_and(|l| l > MAX_SMALL_BYTES) {
            return Err("GitHub API response too large".to_string());
        }
        let body = resp
            .bytes()
            .await
            .map_err(|e| format!("Failed to read GitHub API response: {e}"))?;
        if body.len() as u64 > MAX_SMALL_BYTES {
            return Err("GitHub API response too large".to_string());
        }
        let json: serde_json::Value = serde_json::from_slice(&body)
            .map_err(|e| format!("Failed to parse GitHub API response: {e}"))?;
        if let Some(tag) = json["tag_name"].as_str() {
            if is_valid_tag(tag) {
                return Ok(tag.to_string());
            }
        }
    }

    Err(format!(
        "Failed to determine latest version. Check https://github.com/{REPO}/releases"
    ))
}

fn parse_checksum(checksums_text: &str, archive_name: &str) -> Option<String> {
    for line in checksums_text.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() == 2 {
            let name = parts[1].trim_start_matches('*');
            let name = name.strip_prefix("./").unwrap_or(name);
            if name == archive_name {
                return Some(parts[0].to_ascii_lowercase());
            }
        }
    }
    None
}

fn sha256_file(path: &PathBuf) -> anyhow::Result<String> {
    let mut hasher = Sha256::new();
    let mut file = fs::File::open(path).map_err(|e| anyhow::anyhow!("Failed to open file: {e}"))?;
    io::copy(&mut file, &mut hasher).map_err(|e| anyhow::anyhow!("Failed to read file: {e}"))?;
    Ok(format!("{:x}", hasher.finalize()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn checksum_exact_match_only() {
        let t = "aaa  cora-x-v1.tar.gz.sig\nbbb  evil-cora-x-v1.tar.gz\nccc  *cora-x-v1.tar.gz\n";
        assert_eq!(
            parse_checksum(t, "cora-x-v1.tar.gz").as_deref(),
            Some("ccc")
        );
        assert_eq!(
            parse_checksum("ddd  ./cora-x-v1.tar.gz", "cora-x-v1.tar.gz").as_deref(),
            Some("ddd")
        );
        assert_eq!(
            parse_checksum("aaa  cora-x-v1.tar.gz.sig", "cora-x-v1.tar.gz"),
            None
        );
        assert_eq!(
            parse_checksum("bbb  evil-cora-x-v1.tar.gz", "cora-x-v1.tar.gz"),
            None
        );
    }

    #[test]
    fn skip_checksum_requires_ack() {
        assert_eq!(skip_checksum_decision(None, None), Ok(false));
        assert_eq!(skip_checksum_decision(None, Some("1")), Ok(false));
        assert!(skip_checksum_decision(Some("1"), None).is_err());
        assert!(skip_checksum_decision(Some("true"), Some("no")).is_err());
        assert_eq!(skip_checksum_decision(Some("1"), Some("1")), Ok(true));
    }

    #[test]
    fn tag_validation() {
        assert!(is_valid_tag("v0.14.0"));
        assert!(is_valid_tag("v1.0.0-rc.1"));
        assert!(!is_valid_tag("0.14.0"));
        assert!(!is_valid_tag("v1/../x"));
        assert!(!is_valid_tag("v1?a=b"));
        assert!(!is_valid_tag("v"));
    }

    fn build_tar(entries: &[(&str, tar::EntryType, &[u8], Option<&str>)]) -> Vec<u8> {
        let mut b = tar::Builder::new(Vec::new());
        for (name, ty, data, link) in entries {
            let mut h = tar::Header::new_gnu();
            h.set_entry_type(*ty);
            h.set_size(data.len() as u64);
            h.set_mode(0o755);
            if let Some(l) = link {
                h.set_link_name(l).unwrap();
            }
            h.set_cksum();
            b.append_data(&mut h, name, *data).unwrap();
        }
        let raw = b.into_inner().unwrap();
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        enc.write_all(&raw).unwrap();
        enc.finish().unwrap()
    }

    fn write_archive(dir: &std::path::Path, bytes: &[u8]) -> PathBuf {
        let p = dir.join("a.tar.gz");
        fs::write(&p, bytes).unwrap();
        p
    }

    #[test]
    fn extract_regular_binary_only() {
        let d = tempfile::tempdir().unwrap();
        let out = tempfile::tempdir().unwrap();
        let tgz = build_tar(&[
            ("README", tar::EntryType::Regular, b"hi", None),
            ("cora", tar::EntryType::Regular, b"BIN", None),
        ]);
        let a = write_archive(d.path(), &tgz);
        let p = extract_binary(&a, out.path()).unwrap();
        assert_eq!(fs::read(p).unwrap(), b"BIN");
        assert!(!out.path().join("README").exists());
    }

    #[test]
    fn extract_rejects_symlink_and_hardlink() {
        for ty in [tar::EntryType::Symlink, tar::EntryType::Link] {
            let d = tempfile::tempdir().unwrap();
            let out = tempfile::tempdir().unwrap();
            let tgz = build_tar(&[
                ("evil", ty, b"", Some("/etc/passwd")),
                ("cora", tar::EntryType::Regular, b"BIN", None),
            ]);
            let a = write_archive(d.path(), &tgz);
            assert!(extract_binary(&a, out.path()).is_err());
        }
    }

    #[test]
    fn extract_rejects_symlink_named_cora_and_missing_binary() {
        let d = tempfile::tempdir().unwrap();
        let out = tempfile::tempdir().unwrap();
        let tgz = build_tar(&[("cora", tar::EntryType::Symlink, b"", Some("/bin/sh"))]);
        let a = write_archive(d.path(), &tgz);
        assert!(extract_binary(&a, out.path()).is_err());

        let tgz = build_tar(&[("other", tar::EntryType::Regular, b"x", None)]);
        let a = write_archive(d.path(), &tgz);
        assert!(extract_binary(&a, out.path()).is_err());
    }

    struct FakeCosign {
        available: bool,
        ok: bool,
        calls: std::cell::Cell<u32>,
    }

    impl CosignRunner for FakeCosign {
        fn available(&self) -> bool {
            self.available
        }
        fn verify(&self, bundle: &std::path::Path, _blob: &std::path::Path) -> Result<(), String> {
            self.calls.set(self.calls.get() + 1);
            assert!(bundle.exists());
            if self.ok {
                Ok(())
            } else {
                Err("bad sig".into())
            }
        }
    }

    fn policy(
        require: bool,
        b: BundleState,
        available: bool,
        ok: bool,
    ) -> (Result<SigOutcome, String>, u32) {
        let d = tempfile::tempdir().unwrap();
        let blob = d.path().join("checksums-sha256.txt");
        fs::write(&blob, b"x").unwrap();
        let f = FakeCosign {
            available,
            ok,
            calls: std::cell::Cell::new(0),
        };
        let r = verify_signature_policy(require, b, &f, d.path(), &blob);
        (r, f.calls.get())
    }

    #[test]
    fn signature_policy_matrix() {
        let present = || BundleState::Present(b"{}".to_vec());
        assert_eq!(
            policy(false, present(), true, true),
            (Ok(SigOutcome::Verified), 1)
        );
        assert_eq!(
            policy(true, present(), true, true),
            (Ok(SigOutcome::Verified), 1)
        );
        // cosign rejects => fatal regardless of require
        for req in [false, true] {
            let (r, calls) = policy(req, present(), true, false);
            assert!(r.unwrap_err().contains("FAILED"));
            assert_eq!(calls, 1);
        }
        // cosign missing
        let (r, calls) = policy(false, present(), false, true);
        assert!(matches!(r, Ok(SigOutcome::Unverified(ref m)) if m.contains("cosign not found")));
        assert_eq!(calls, 0);
        assert!(policy(true, present(), false, true).0.is_err());
        // bundle absent (older release)
        assert!(matches!(
            policy(false, BundleState::Absent, true, true).0,
            Ok(SigOutcome::Unverified(_))
        ));
        assert!(policy(true, BundleState::Absent, true, true).0.is_err());
        // other fetch errors are always fatal
        for req in [false, true] {
            assert!(
                policy(req, BundleState::Error("HTTP 500".into()), true, true)
                    .0
                    .is_err()
            );
        }
    }

    #[test]
    fn require_signature_parsing() {
        assert_eq!(parse_require_signature(None), Ok(false));
        assert_eq!(parse_require_signature(Some("0")), Ok(false));
        assert_eq!(parse_require_signature(Some("1")), Ok(true));
        assert_eq!(parse_require_signature(Some("true")), Ok(true));
        assert!(parse_require_signature(Some("yes")).is_err());
    }

    #[test]
    fn signature_constants() {
        assert_eq!(
            bundle_url("v1.2.3"),
            "https://github.com/codecoradev/cora-code/releases/download/v1.2.3/checksums-sha256.txt.sigstore.json"
        );
        assert_eq!(
            cosign_identity_regexp(),
            "^https://github.com/codecoradev/cora-code/\\.github/workflows/release\\.yml@refs/tags/v"
        );
        assert_eq!(
            COSIGN_OIDC_ISSUER,
            "https://token.actions.githubusercontent.com"
        );
    }
}