nomograph-kit 0.10.1

Verified tool registry manager -- manages developer toolchains from git-based registries
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
use anyhow::{Context, Result};
use sha2::{Digest, Sha256};
use std::io::Read;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use crate::platform::Platform;
use crate::tool::{ChecksumFormat, SignatureMethod, ToolDef};

/// Outcome of a verification attempt.
#[derive(Debug, Clone)]
pub enum VerifyResult {
    /// Verification passed.
    Verified { method: String, sha256: String },
    /// Verification explicitly failed -- hard stop.
    Failed { method: String, reason: String },
    /// No verification method available -- warning only.
    Unavailable { reason: String },
}

impl VerifyResult {
    #[allow(dead_code)]
    pub fn is_verified(&self) -> bool {
        matches!(self, Self::Verified { .. })
    }

    #[allow(dead_code)]
    pub fn is_failed(&self) -> bool {
        matches!(self, Self::Failed { .. })
    }
}

/// Compute the hex-encoded SHA256 digest of a file.
pub fn compute_sha256(path: &Path) -> Result<String> {
    let mut file =
        std::fs::File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 8192];
    loop {
        let n = file
            .read(&mut buf)
            .with_context(|| format!("read error on {}", path.display()))?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hex::encode(hasher.finalize()))
}

/// Extract the expected checksum for an asset from a checksum file.
///
/// Returns `Ok(Some(hash))` if found, `Ok(None)` if the asset is not listed.
pub fn parse_checksum_file(
    content: &str,
    asset_name: &str,
    format: &ChecksumFormat,
) -> Result<Option<String>> {
    match format {
        ChecksumFormat::Sha256 => {
            // Lines of `hash  filename` (two-space separator).
            // Match by filename suffix so that `./filename` or path-prefixed entries
            // still match the bare asset name.
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                // Split on the first run of whitespace (standard sha256sum format
                // uses two spaces, but be tolerant of tabs and single spaces too).
                let mut parts = line.splitn(2, char::is_whitespace);
                let hash = match parts.next() {
                    Some(h) => h.trim(),
                    None => continue,
                };
                let filename = match parts.next() {
                    Some(f) => f.trim().trim_start_matches('*'),
                    None => continue,
                };

                // Match if the filename ends with the asset name (handles ./prefix).
                if filename == asset_name || filename.ends_with(&format!("/{asset_name}")) {
                    validate_hex_hash(hash)?;
                    return Ok(Some(hash.to_lowercase()));
                }
            }
            Ok(None)
        }
        ChecksumFormat::Sha256PerAsset => {
            // The entire content is a single hash (optionally followed by
            // whitespace and a filename). Take the first non-whitespace token.
            let hash = content
                .split_whitespace()
                .next()
                .context("checksum file is empty")?;
            validate_hex_hash(hash)?;
            Ok(Some(hash.to_lowercase()))
        }
    }
}

/// Ensure a string looks like a valid hex-encoded SHA256 hash.
fn validate_hex_hash(h: &str) -> Result<()> {
    if h.len() != 64 {
        anyhow::bail!("expected 64-character SHA256 hash, got {} characters", h.len());
    }
    if !h.chars().all(|c| c.is_ascii_hexdigit()) {
        anyhow::bail!("hash contains non-hex characters: {h}");
    }
    Ok(())
}

/// Build an HTTPS-only reqwest blocking client.
fn https_client() -> Result<reqwest::blocking::Client> {
    reqwest::blocking::Client::builder()
        .https_only(true)
        .timeout(Duration::from_secs(60))
        .redirect(reqwest::redirect::Policy::limited(5))
        .build()
        .context("failed to build HTTP client")
}

/// F13: Resolve the expected SHA256 for a tool+platform from upstream.
/// Returns the expected hash -- does NOT compare against an actual binary.
/// Callers must compare the result themselves.
/// Checks inline checksums first, falls back to downloading upstream checksum file.
pub fn resolve_expected_checksum(
    tool: &ToolDef,
    platform: Platform,
) -> Result<VerifyResult> {
    // First, check for inline pre-computed checksums.
    let asset_name = match tool.asset_for(platform) {
        Some(a) => a,
        None => {
            return Ok(VerifyResult::Unavailable {
                reason: format!("no asset defined for platform {platform}"),
            });
        }
    };

    // Determine expected hash: prefer inline checksums map, fall back to
    // downloading the upstream checksum file.
    let expected = if let Some(inline) = tool.checksums.get(platform.key()) {
        inline.to_lowercase()
    } else {
        let checksum_url = match tool.checksum_url() {
            Some(u) => u,
            None => {
                return Ok(VerifyResult::Unavailable {
                    reason: "no checksum file configured".to_string(),
                });
            }
        };

        let format = tool
            .checksum
            .as_ref()
            .map(|c| &c.format)
            .unwrap_or(&ChecksumFormat::Sha256);

        let client = https_client()?;
        let resp = client
            .get(&checksum_url)
            .send()
            .with_context(|| format!("failed to download checksum file: {checksum_url}"))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let reason = if status == reqwest::StatusCode::FORBIDDEN
                && checksum_url.contains("gitlab.com/api/v4/projects/")
                && checksum_url.contains("/packages/")
            {
                format!(
                    "checksum file download failed: HTTP {} -- check that packages_enabled is true on the project",
                    status
                )
            } else {
                format!("checksum file download failed: HTTP {}", status)
            };
            return Ok(VerifyResult::Failed {
                method: "sha256".to_string(),
                reason,
            });
        }

        let body = resp
            .text()
            .context("failed to read checksum file response body")?;

        match parse_checksum_file(&body, &asset_name, format)? {
            Some(h) => h,
            None => {
                return Ok(VerifyResult::Failed {
                    method: "sha256".to_string(),
                    reason: format!(
                        "asset '{asset_name}' not found in checksum file"
                    ),
                });
            }
        }
    };

    Ok(VerifyResult::Verified {
        method: "sha256".to_string(),
        sha256: expected,
    })
}

/// Verify a binary using cosign keyless (sigstore) verification.
///
/// Shells out to `cosign verify-blob` with the bundle downloaded from
/// `bundle_url`. Returns `true` if the signature is valid.
pub fn verify_cosign(
    binary_path: &Path,
    bundle_url: &str,
    issuer: &str,
    identity: &str,
) -> Result<bool> {
    // Download the bundle to a temp file.
    let client = https_client()?;
    let resp = client
        .get(bundle_url)
        .send()
        .with_context(|| format!("failed to download cosign bundle: {bundle_url}"))?;
    if !resp.status().is_success() {
        anyhow::bail!(
            "cosign bundle download failed: HTTP {} from {bundle_url}",
            resp.status()
        );
    }
    let bundle_bytes = resp.bytes().context("failed to read bundle body")?;

    let tmp_dir =
        tempfile::tempdir().context("failed to create temp dir for cosign bundle")?;
    let bundle_path = tmp_dir.path().join("bundle.json");
    std::fs::write(&bundle_path, &bundle_bytes)
        .context("failed to write cosign bundle to temp file")?;

    // GitLab CI cosign bundles embed the full pipeline identity as the
    // certificate SAN, e.g. "https://gitlab.com/org/repo//.gitlab-ci.yml@refs/tags/v1.0.0".
    // The tool definition stores only the project URL prefix (e.g.
    // "https://gitlab.com/org/repo"). Use --certificate-identity-regexp
    // to match the prefix, anchored so it cannot match unrelated projects.
    let identity_pattern = format!("^{}(/.*)?$", regex::escape(identity));

    let output = Command::new("cosign")
        .arg("verify-blob")
        .arg("--bundle")
        .arg(&bundle_path)
        .arg("--certificate-oidc-issuer")
        .arg(issuer)
        .arg("--certificate-identity-regexp")
        .arg(&identity_pattern)
        .arg(binary_path)
        .output()
        .context("failed to execute cosign -- is it installed?")?;

    Ok(output.status.success())
}

/// Verify a binary using GitHub artifact attestation.
///
/// Shells out to `gh attestation verify`. Returns `true` if attestation
/// is valid.
pub fn verify_gh_attestation(binary_path: &Path, repo: &str) -> Result<bool> {
    let output = Command::new("gh")
        .arg("attestation")
        .arg("verify")
        .arg(binary_path)
        .arg("--repo")
        .arg(repo)
        .output()
        .context("failed to execute gh -- is it installed?")?;

    Ok(output.status.success())
}

/// Resolve the installed binary path using `mise which`.
///
/// Falls back to heuristic path guessing if mise is not available.
pub fn resolve_binary_path(tool: &ToolDef) -> Option<std::path::PathBuf> {
    let bin_name = tool.bin_name();

    // Primary: ask mise for the authoritative path.
    if let Ok(output) = Command::new("mise")
        .args(["which", bin_name])
        .output()
        && output.status.success()
    {
        let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !path_str.is_empty() {
            let path = std::path::PathBuf::from(&path_str);
            if path.exists() {
                return Some(path);
            }
        }
    }

    None
}

/// Check whether the download asset for this tool+platform is an archive.
///
/// When the asset is an archive (.tar.gz, .zip, .tar.xz, .pkg, etc.),
/// the registry checksums are for the archive, not the extracted binary.
/// Checksum verification against the installed binary is not meaningful
/// in that case.
pub fn is_archive_asset(tool: &ToolDef, platform: Platform) -> bool {
    let asset = match tool.asset_for(platform) {
        Some(a) => a,
        None => return false,
    };
    let lower = asset.to_lowercase();
    lower.ends_with(".tar.gz")
        || lower.ends_with(".tgz")
        || lower.ends_with(".tar.xz")
        || lower.ends_with(".tar.bz2")
        || lower.ends_with(".zip")
        || lower.ends_with(".pkg")
        || lower.ends_with(".deb")
        || lower.ends_with(".rpm")
}

/// Determine the best verification method from the tool definition and run it.
///
/// Priority order:
///   1. cosign-keyless (sigstore)
///   2. github-attestation (gh attestation verify)
///   3. sha256 checksum
///   4. none (unavailable)
///
/// For methods that also support checksums, we compute and include the sha256
/// of the installed binary in the result regardless.
///
/// `binary_path` is the resolved path to the installed binary (use
/// `resolve_binary_path` or `mise which` to obtain it).
pub fn verify_tool(
    tool: &ToolDef,
    platform: Platform,
    binary_path: &Path,
) -> Result<VerifyResult> {
    if !binary_path.exists() {
        return Ok(VerifyResult::Failed {
            method: "pre-check".to_string(),
            reason: format!("binary not found at {}", binary_path.display()),
        });
    }

    // Always compute the installed binary's SHA256 for the result.
    let actual_sha = compute_sha256(binary_path)?;

    // When the download asset is an archive (.tar.gz, .zip, etc.), the
    // registry checksums and signatures refer to the archive, not the
    // extracted binary. Checksum comparison against the installed binary
    // is not meaningful; we record the binary hash but cannot verify it
    // against the upstream archive checksum.
    let archive = is_archive_asset(tool, platform);

    // -- 1. Cosign keyless --
    // Cosign bundles sign the download artifact. For bare binaries this
    // is the binary itself; for archives it signs the archive.
    if let Some(ref sig) = tool.signature
        && sig.method == SignatureMethod::CosignKeyless
        && !archive
    {
            let issuer = sig
                .issuer
                .as_deref()
                .context("cosign-keyless requires 'issuer' in signature config")?;
            let identity = sig
                .identity
                .as_deref()
                .context("cosign-keyless requires 'identity' in signature config")?;

            // Construct the bundle URL (same base as the binary, with .bundle suffix).
            // Append .bundle to the full URL rather than using replace(), which
            // could corrupt the URL if the asset name appears in the path prefix.
            let bundle_url = tool
                .url_for(platform)
                .map(|u| format!("{u}.bundle"))
                .context("cannot determine bundle URL")?;

            match verify_cosign(binary_path, &bundle_url, issuer, identity) {
                Ok(true) => {
                    // Cosign passed; still verify checksum if available.
                    let checksum_result = verify_checksum_against_binary(tool, platform, &actual_sha);
                    if let Some(VerifyResult::Failed { method, reason }) = checksum_result {
                        return Ok(VerifyResult::Failed {
                            method: format!("cosign-keyless+{method}"),
                            reason,
                        });
                    }
                    return Ok(VerifyResult::Verified {
                        method: "cosign-keyless".to_string(),
                        sha256: actual_sha,
                    });
                }
                Ok(false) => {
                    return Ok(VerifyResult::Failed {
                        method: "cosign-keyless".to_string(),
                        reason: "cosign verify-blob returned non-zero".to_string(),
                    });
                }
                Err(e) => {
                    // cosign not installed or other execution error -- fall through
                    eprintln!(
                        "  warning: cosign verification failed ({e:#}), falling back"
                    );
                }
            }
    }

    // -- 2. GitHub attestation --
    // gh attestation verify operates on the download artifact, not extracted binaries.
    if let Some(ref sig) = tool.signature
        && sig.method == SignatureMethod::GithubAttestation
        && !archive
    {
            let repo = tool
                .repo
                .as_deref()
                .context("github-attestation requires 'repo' on tool definition")?;

            match verify_gh_attestation(binary_path, repo) {
                Ok(true) => {
                    let checksum_result = verify_checksum_against_binary(tool, platform, &actual_sha);
                    if let Some(VerifyResult::Failed { method, reason }) = checksum_result {
                        return Ok(VerifyResult::Failed {
                            method: format!("github-attestation+{method}"),
                            reason,
                        });
                    }
                    return Ok(VerifyResult::Verified {
                        method: "github-attestation".to_string(),
                        sha256: actual_sha,
                    });
                }
                Ok(false) => {
                    return Ok(VerifyResult::Failed {
                        method: "github-attestation".to_string(),
                        reason: "gh attestation verify returned non-zero".to_string(),
                    });
                }
                Err(e) => {
                    eprintln!(
                        "  warning: gh attestation check failed ({e:#}), falling back"
                    );
                }
            }
    }

    // -- 3. SHA256 checksum --
    // Only compare checksums when the download artifact is the bare binary.
    // For archive-distributed tools, the registry checksum is for the
    // archive, not the extracted binary.
    if !archive && (tool.checksum.is_some() || !tool.checksums.is_empty()) {
        let checksum_result = resolve_expected_checksum(tool, platform)?;
        match checksum_result {
            VerifyResult::Verified {
                method,
                sha256: expected,
            } => {
                if actual_sha == expected {
                    return Ok(VerifyResult::Verified {
                        method,
                        sha256: actual_sha,
                    });
                } else {
                    return Ok(VerifyResult::Failed {
                        method,
                        reason: format!(
                            "checksum mismatch: expected {expected}, got {actual_sha}"
                        ),
                    });
                }
            }
            other => return Ok(other),
        }
    }

    // -- 4. Archive-distributed tool with a binary hash --
    // We found the binary and computed its hash, but cannot verify it
    // against upstream (checksums are for the archive). Report as
    // Verified with the binary hash for lockfile use.
    if archive {
        return Ok(VerifyResult::Verified {
            method: "binary-hash".to_string(),
            sha256: actual_sha,
        });
    }

    // -- 5. Nothing available --
    Ok(VerifyResult::Unavailable {
        reason: "no checksum or signature method configured".to_string(),
    })
}

/// Helper: verify a checksum against an already-computed binary hash.
/// Returns `Some(VerifyResult::Failed)` on mismatch, `None` on match or
/// if no checksum is configured.
fn verify_checksum_against_binary(
    tool: &ToolDef,
    platform: Platform,
    actual_sha: &str,
) -> Option<VerifyResult> {
    if tool.checksum.is_none() && tool.checksums.is_empty() {
        return None;
    }
    match resolve_expected_checksum(tool, platform) {
        Ok(VerifyResult::Verified { sha256: expected, .. }) => {
            if actual_sha != expected {
                Some(VerifyResult::Failed {
                    method: "sha256".to_string(),
                    reason: format!(
                        "checksum mismatch: expected {expected}, got {actual_sha}"
                    ),
                })
            } else {
                None
            }
        }
        Ok(VerifyResult::Failed { method, reason }) => Some(VerifyResult::Failed { method, reason }),
        _ => None,
    }
}

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

    #[test]
    fn sha256_known_data() {
        // SHA256 of "hello\n" (echo "hello") is well-known.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hello.txt");
        {
            let mut f = std::fs::File::create(&path).unwrap();
            f.write_all(b"hello\n").unwrap();
        }
        let hash = compute_sha256(&path).unwrap();
        assert_eq!(
            hash,
            "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03"
        );
    }

    #[test]
    fn sha256_empty_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("empty");
        std::fs::File::create(&path).unwrap();
        let hash = compute_sha256(&path).unwrap();
        // SHA256 of empty input.
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn parse_checksum_sha256_standard() {
        let content = "\
a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2  gh_2.89.0_macOS_arm64.zip
1111111111111111111111111111111111111111111111111111111111111111  gh_2.89.0_linux_amd64.tar.gz
";
        let result = parse_checksum_file(
            content,
            "gh_2.89.0_macOS_arm64.zip",
            &ChecksumFormat::Sha256,
        )
        .unwrap();
        assert_eq!(
            result,
            Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".to_string())
        );
    }

    #[test]
    fn parse_checksum_sha256_not_found() {
        let content = "\
a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2  other-file.tar.gz
";
        let result = parse_checksum_file(
            content,
            "missing-asset.zip",
            &ChecksumFormat::Sha256,
        )
        .unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn parse_checksum_sha256_per_asset() {
        let content =
            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2\n";
        let result = parse_checksum_file(
            content,
            "anything.tar.gz",
            &ChecksumFormat::Sha256PerAsset,
        )
        .unwrap();
        assert_eq!(
            result,
            Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".to_string())
        );
    }

    #[test]
    fn parse_checksum_sha256_per_asset_with_filename() {
        let content =
            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2  muxr-darwin-arm64\n";
        let result = parse_checksum_file(
            content,
            "muxr-darwin-arm64",
            &ChecksumFormat::Sha256PerAsset,
        )
        .unwrap();
        assert_eq!(
            result,
            Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".to_string())
        );
    }

    #[test]
    fn parse_checksum_rejects_bad_hash() {
        // Too short.
        let content = "deadbeef  some-file.tar.gz\n";
        let result =
            parse_checksum_file(content, "some-file.tar.gz", &ChecksumFormat::Sha256);
        assert!(result.is_err());
    }

    #[test]
    fn parse_checksum_skips_comments() {
        let content = "\
# This is a comment
a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2  target.bin
";
        let result = parse_checksum_file(
            content,
            "target.bin",
            &ChecksumFormat::Sha256,
        )
        .unwrap();
        assert_eq!(
            result,
            Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".to_string())
        );
    }

    #[test]
    fn checksum_mismatch_detection() {
        // Simulate: expected vs actual differ.
        let expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let actual = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        assert_ne!(expected, actual);

        // Create a file whose hash will not match the "expected" value.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("binary");
        {
            let mut f = std::fs::File::create(&path).unwrap();
            f.write_all(b"some binary content").unwrap();
        }
        let actual_hash = compute_sha256(&path).unwrap();
        assert_ne!(actual_hash, expected, "hash should not match fabricated expected value");
    }

    #[test]
    fn validate_hex_hash_accepts_valid() {
        let valid = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
        assert!(validate_hex_hash(valid).is_ok());
    }

    #[test]
    fn validate_hex_hash_rejects_short() {
        assert!(validate_hex_hash("abc123").is_err());
    }

    #[test]
    fn validate_hex_hash_rejects_non_hex() {
        let bad = "zzzz23d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
        assert!(validate_hex_hash(bad).is_err());
    }

    fn make_tool(name: &str, assets: Vec<(&str, &str)>) -> crate::tool::ToolDef {
        crate::tool::ToolDef {
            name: name.to_string(),
            description: None,
            source: crate::tool::Source::Github,
            version: "1.0.0".to_string(),
            tag_prefix: "v".to_string(),
            bin: None,
            tier: crate::tool::Tier::Low,
            repo: Some("owner/repo".to_string()),
            project_id: None,
            package: None,
            crate_name: None,
            aqua: None,
            assets: assets
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            checksum: None,
            checksums: std::collections::HashMap::new(),
            signature: None,
        }
    }

    #[test]
    fn is_archive_detects_tar_gz() {
        let tool = make_tool("gh", vec![("macos-arm64", "gh_1.0.0_macOS_arm64.tar.gz")]);
        assert!(is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn is_archive_detects_zip() {
        let tool = make_tool("gh", vec![("macos-arm64", "gh_1.0.0_macOS_arm64.zip")]);
        assert!(is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn is_archive_detects_tar_xz() {
        let tool = make_tool("sc", vec![("macos-arm64", "shellcheck-v1.0.0.darwin.aarch64.tar.xz")]);
        assert!(is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn is_archive_detects_pkg() {
        let tool = make_tool("hugo", vec![("macos-arm64", "hugo_extended_1.0.0_darwin-universal.pkg")]);
        assert!(is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn is_archive_bare_binary_is_not_archive() {
        let tool = make_tool("muxr", vec![("macos-arm64", "muxr-darwin-arm64")]);
        assert!(!is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn is_archive_no_asset_is_not_archive() {
        let tool = make_tool("nothing", vec![]);
        assert!(!is_archive_asset(&tool, Platform::MacosArm64));
    }

    #[test]
    fn verify_tool_bare_binary_with_inline_checksum() {
        // Create a fake binary and provide its actual checksum as the inline checksum.
        let dir = tempfile::tempdir().unwrap();
        let binary = dir.path().join("test-tool");
        {
            let mut f = std::fs::File::create(&binary).unwrap();
            f.write_all(b"fake binary content").unwrap();
        }
        let expected_hash = compute_sha256(&binary).unwrap();

        let mut tool = make_tool("test-tool", vec![("macos-arm64", "test-tool-darwin-arm64")]);
        tool.checksums.insert("macos-arm64".to_string(), expected_hash.clone());

        let result = verify_tool(&tool, Platform::MacosArm64, &binary).unwrap();
        assert!(result.is_verified());
        match result {
            VerifyResult::Verified { method, sha256 } => {
                assert_eq!(method, "sha256");
                assert_eq!(sha256, expected_hash);
            }
            _ => panic!("expected Verified"),
        }
    }

    #[test]
    fn verify_tool_archive_asset_returns_binary_hash() {
        // For archive-distributed tools, verify_tool should return the
        // binary hash without comparing against the archive checksum.
        let dir = tempfile::tempdir().unwrap();
        let binary = dir.path().join("gh");
        {
            let mut f = std::fs::File::create(&binary).unwrap();
            f.write_all(b"fake gh binary").unwrap();
        }
        let expected_hash = compute_sha256(&binary).unwrap();

        let mut tool = make_tool("gh", vec![("macos-arm64", "gh_1.0.0_macOS_arm64.zip")]);
        // This checksum is for the zip, not the binary -- should NOT cause a mismatch.
        tool.checksums.insert(
            "macos-arm64".to_string(),
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
        );

        let result = verify_tool(&tool, Platform::MacosArm64, &binary).unwrap();
        assert!(result.is_verified());
        match result {
            VerifyResult::Verified { method, sha256 } => {
                assert_eq!(method, "binary-hash");
                assert_eq!(sha256, expected_hash);
            }
            _ => panic!("expected Verified with binary-hash method"),
        }
    }

    #[test]
    fn verify_tool_missing_binary_fails() {
        let tool = make_tool("missing", vec![("macos-arm64", "missing-darwin-arm64")]);
        let result = verify_tool(
            &tool,
            Platform::MacosArm64,
            std::path::Path::new("/nonexistent/path/to/binary"),
        )
        .unwrap();
        assert!(result.is_failed());
    }
}