jarvy 0.0.5

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
Documentation
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
//! Signature and checksum verification for updates
//!
//! Provides secure verification of downloaded binaries.

#![allow(dead_code)] // Public API for signature verification

use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::Read;
use std::path::Path;

/// Verify a file's SHA256 checksum
pub fn verify_checksum(file_path: &Path, expected: &str) -> Result<bool, VerifyError> {
    let actual = calculate_sha256(file_path)?;
    Ok(actual.to_lowercase() == expected.to_lowercase())
}

/// Calculate SHA256 hash of a file
pub fn calculate_sha256(file_path: &Path) -> Result<String, VerifyError> {
    let mut file = File::open(file_path).map_err(VerifyError::Io)?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];

    loop {
        let n = file.read(&mut buffer).map_err(VerifyError::Io)?;
        if n == 0 {
            break;
        }
        hasher.update(&buffer[..n]);
    }

    Ok(hex::encode(hasher.finalize()))
}

/// Parse a checksums file (SHA256SUMS format)
/// Returns a list of (checksum, filename) tuples
pub fn parse_checksums(content: &str) -> Vec<(String, String)> {
    content
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                return None;
            }

            // Format: "checksum  filename" or "checksum *filename"
            let mut parts = line.splitn(2, |c: char| c.is_whitespace());
            let checksum = parts.next()?.trim();
            let filename = parts.next()?.trim().trim_start_matches('*');

            if checksum.len() == 64 && !filename.is_empty() {
                Some((checksum.to_string(), filename.to_string()))
            } else {
                None
            }
        })
        .collect()
}

/// Find checksum for a specific file in checksums content
pub fn find_checksum(checksums_content: &str, filename: &str) -> Option<String> {
    let checksums = parse_checksums(checksums_content);
    checksums
        .into_iter()
        .find(|(_, name)| name == filename || name.ends_with(filename))
        .map(|(sum, _)| sum)
}

/// Anchored Fulcio cert-identity regex. Anchors the host (`github.com`),
/// the repo path, the workflow file, and the tag-ref so a Fulcio cert whose
/// Subject merely *contains* `github.com/bearbinary/jarvy` (e.g. an attacker
/// fork's workflow URL with that substring) is rejected.
pub(crate) const COSIGN_CERT_IDENTITY_REGEX: &str = concat!(
    r"^https://github\.com/bearbinary/jarvy/\.github/workflows/[^@]+@",
    r"refs/tags/v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z\.\-]+)?$",
);

/// Result of a Sigstore verification attempt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignatureOutcome {
    /// `cosign verify-blob` succeeded.
    Verified,
    /// `cosign` is not on PATH.
    CosignMissing,
    /// `.sig` or `.pem` files were not found alongside the artifact.
    SignatureFilesMissing,
    /// Cosign ran and rejected the artifact.
    Rejected(String),
}

/// Verify a file's Sigstore signature using cosign.
///
/// Returns a `SignatureOutcome` describing what happened — fail-OPEN handling
/// (treating cosign-missing or sig-missing as success) is **the caller's
/// decision**. The installer fails closed unless explicit override is granted.
pub fn verify_sigstore_signature(file_path: &Path) -> Result<SignatureOutcome, VerifyError> {
    use std::process::Command;

    // Check if cosign is available
    if Command::new("cosign").arg("version").output().is_err() {
        tracing::warn!(
            event = "update.signature.skipped",
            reason = "cosign_missing",
            file = %file_path.display(),
        );
        return Ok(SignatureOutcome::CosignMissing);
    }

    let sig_path = file_path.with_extension(format!(
        "{}.sig",
        file_path.extension().unwrap_or_default().to_string_lossy()
    ));
    let cert_path = file_path.with_extension(format!(
        "{}.pem",
        file_path.extension().unwrap_or_default().to_string_lossy()
    ));

    if !sig_path.exists() || !cert_path.exists() {
        tracing::warn!(
            event = "update.signature.skipped",
            reason = "sig_files_missing",
            file = %file_path.display(),
        );
        return Ok(SignatureOutcome::SignatureFilesMissing);
    }

    let output = Command::new("cosign")
        .args([
            "verify-blob",
            "--signature",
            &sig_path.to_string_lossy(),
            "--certificate",
            &cert_path.to_string_lossy(),
            "--certificate-identity-regexp",
            COSIGN_CERT_IDENTITY_REGEX,
            "--certificate-oidc-issuer",
            "https://token.actions.githubusercontent.com",
        ])
        .arg(file_path)
        .output()
        .map_err(VerifyError::Io)?;

    if output.status.success() {
        tracing::info!(
            event = "update.signature.verified",
            file = %file_path.display(),
        );
        Ok(SignatureOutcome::Verified)
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        tracing::error!(
            event = "update.signature.failed",
            file = %file_path.display(),
            error = %stderr,
        );
        Ok(SignatureOutcome::Rejected(stderr))
    }
}

/// Decide whether a `SignatureOutcome` should permit installation to proceed.
///
/// `allow_unsigned` should be set only when the operator has explicitly opted
/// into unsigned updates (CLI `--allow-unsigned` flag or
/// `JARVY_ALLOW_UNSIGNED_UPDATE=1` env). Default (`false`) is fail-closed.
pub fn signature_outcome_is_acceptable(
    outcome: &SignatureOutcome,
    allow_unsigned: bool,
) -> Result<(), String> {
    match outcome {
        SignatureOutcome::Verified => Ok(()),
        SignatureOutcome::CosignMissing => {
            if allow_unsigned {
                Ok(())
            } else {
                Err(
                    "cosign is not installed; install it (https://docs.sigstore.dev/cosign/) \
                     or re-run with --allow-unsigned to accept supply-chain risk"
                        .to_string(),
                )
            }
        }
        SignatureOutcome::SignatureFilesMissing => {
            if allow_unsigned {
                Ok(())
            } else {
                Err(
                    "release does not include .sig/.pem files; refusing to install \
                     unsigned binary. Re-run with --allow-unsigned to override."
                        .to_string(),
                )
            }
        }
        SignatureOutcome::Rejected(stderr) => Err(format!(
            "Sigstore verification rejected the artifact: {stderr}"
        )),
    }
}

/// Read `JARVY_ALLOW_UNSIGNED_UPDATE` and treat any value that is not "0",
/// "false", or empty as "permit unsigned updates."
pub fn unsigned_override_from_env() -> bool {
    match std::env::var("JARVY_ALLOW_UNSIGNED_UPDATE") {
        Ok(v) => {
            let t = v.trim().to_ascii_lowercase();
            !t.is_empty() && t != "0" && t != "false" && t != "no"
        }
        Err(_) => false,
    }
}

/// Errors during verification
#[derive(Debug, thiserror::Error)]
pub enum VerifyError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Checksum mismatch")]
    ChecksumMismatch,

    #[error("Checksum not found for file: {0}")]
    ChecksumNotFound(String),

    #[error("Signature verification failed: {0}")]
    SignatureInvalid(String),
}

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

    #[test]
    fn test_calculate_sha256() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");

        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"hello world").unwrap();
        drop(file);

        let hash = calculate_sha256(&file_path).unwrap();
        assert_eq!(
            hash,
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );
    }

    #[test]
    fn test_verify_checksum() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");

        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"hello world").unwrap();
        drop(file);

        let valid = verify_checksum(
            &file_path,
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
        )
        .unwrap();
        assert!(valid);

        let invalid = verify_checksum(
            &file_path,
            "0000000000000000000000000000000000000000000000000000000000000000",
        )
        .unwrap();
        assert!(!invalid);
    }

    #[test]
    fn test_parse_checksums() {
        // SHA256 hashes are 64 hex characters
        let content = r#"
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  jarvy-darwin-aarch64.tar.gz
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb  jarvy-linux-x86_64.tar.gz
# Comment line
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc *jarvy-windows-x86_64.zip
"#;

        let checksums = parse_checksums(content);
        assert_eq!(checksums.len(), 3);
        assert_eq!(
            checksums[0].0,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        assert_eq!(checksums[0].1, "jarvy-darwin-aarch64.tar.gz");
        assert_eq!(checksums[2].1, "jarvy-windows-x86_64.zip");
    }

    #[test]
    fn cert_identity_regex_is_anchored() {
        let re = regex::Regex::new(COSIGN_CERT_IDENTITY_REGEX).expect("valid regex");
        // Legitimate identity from a release-tag workflow.
        assert!(re.is_match(
            "https://github.com/bearbinary/jarvy/.github/workflows/release.yml@refs/tags/v1.2.3"
        ));
        assert!(re.is_match(
            "https://github.com/bearbinary/jarvy/.github/workflows/release.yml@refs/tags/v1.2.3-rc.1"
        ));
        // Substring attack: attacker repo's path happens to contain the substring.
        assert!(!re.is_match(
            "https://github.com/attacker/repo/.github/workflows/foo.yml@refs/heads/main\
             github.com/bearbinary/jarvy"
        ));
        // Non-tag ref must be rejected (workflow-on-branch).
        assert!(!re.is_match(
            "https://github.com/bearbinary/jarvy/.github/workflows/release.yml@refs/heads/main"
        ));
        // Wrong host.
        assert!(!re.is_match(
            "https://gitlab.com/bearbinary/jarvy/.github/workflows/release.yml@refs/tags/v1.0.0"
        ));
    }

    #[test]
    fn cosign_missing_is_not_acceptable_by_default() {
        let outcome = SignatureOutcome::CosignMissing;
        assert!(signature_outcome_is_acceptable(&outcome, false).is_err());
    }

    #[test]
    fn cosign_missing_acceptable_with_override() {
        let outcome = SignatureOutcome::CosignMissing;
        assert!(signature_outcome_is_acceptable(&outcome, true).is_ok());
    }

    #[test]
    fn sig_files_missing_is_not_acceptable_by_default() {
        let outcome = SignatureOutcome::SignatureFilesMissing;
        assert!(signature_outcome_is_acceptable(&outcome, false).is_err());
    }

    #[test]
    fn rejected_outcome_never_acceptable() {
        let outcome = SignatureOutcome::Rejected("bad cert".into());
        assert!(signature_outcome_is_acceptable(&outcome, true).is_err());
        assert!(signature_outcome_is_acceptable(&outcome, false).is_err());
    }

    #[test]
    fn verified_outcome_always_acceptable() {
        let outcome = SignatureOutcome::Verified;
        assert!(signature_outcome_is_acceptable(&outcome, false).is_ok());
        assert!(signature_outcome_is_acceptable(&outcome, true).is_ok());
    }

    #[test]
    fn unsigned_override_env_parsing() {
        // Use unique var per test concern; the underlying impl reads
        // JARVY_ALLOW_UNSIGNED_UPDATE so we set it directly.
        // SAFETY: tests run in parallel by default. We restore before exit.
        let key = "JARVY_ALLOW_UNSIGNED_UPDATE";
        let prev = std::env::var(key).ok();

        #[allow(unsafe_code)]
        unsafe {
            std::env::remove_var(key);
        }
        assert!(!unsigned_override_from_env());

        for truthy in ["1", "true", "yes", "TRUE", "Y"] {
            #[allow(unsafe_code)]
            unsafe {
                std::env::set_var(key, truthy);
            }
            // Note: "Y" is not in the falsy list, so it's truthy by default.
            assert!(
                unsigned_override_from_env(),
                "expected truthy for value {truthy:?}"
            );
        }

        for falsy in ["0", "false", "no", ""] {
            #[allow(unsafe_code)]
            unsafe {
                std::env::set_var(key, falsy);
            }
            assert!(
                !unsigned_override_from_env(),
                "expected falsy for value {falsy:?}"
            );
        }

        // Restore.
        match prev {
            Some(v) => {
                #[allow(unsafe_code)]
                unsafe {
                    std::env::set_var(key, v);
                }
            }
            None => {
                #[allow(unsafe_code)]
                unsafe {
                    std::env::remove_var(key);
                }
            }
        }
    }

    #[test]
    fn test_find_checksum() {
        // SHA256 hashes are 64 hex characters
        let content = r#"
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  jarvy-darwin-aarch64.tar.gz
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb  jarvy-linux-x86_64.tar.gz
"#;

        let found = find_checksum(content, "jarvy-darwin-aarch64.tar.gz");
        assert_eq!(
            found,
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string())
        );

        let not_found = find_checksum(content, "nonexistent.tar.gz");
        assert_eq!(not_found, None);
    }
}