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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Secret prompting and handling
//!
//! Handles secret values with:
//! - Hidden password input using rpassword
//! - Loading secrets from files
//! - Environment variable fallback
//! - CI mode skipping

use std::collections::HashMap;
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use thiserror::Error;

use super::expand::{EnvContext, expand_path};
use crate::config::SecretValue;

/// Errors that can occur during secret handling
#[derive(Error, Debug)]
pub enum SecretError {
    #[error("Failed to read secret from file: {0}")]
    FileReadError(#[from] std::io::Error),
    #[error("Required secret '{0}' was not provided")]
    MissingRequired(String),
    #[error("Failed to read user input")]
    InputError,
    #[error("Secret file not found: {0}")]
    FileNotFound(String),
}

/// Configuration for secret collection
#[derive(Debug, Clone)]
pub struct SecretsConfig {
    /// Whether we're running in CI mode (skip prompts)
    pub ci_mode: bool,
    /// Whether to fail on missing required secrets
    pub fail_on_missing: bool,
}

impl Default for SecretsConfig {
    fn default() -> Self {
        Self {
            ci_mode: std::env::var("CI").is_ok()
                || std::env::var("JARVY_CI").is_ok()
                || std::env::var("JARVY_TEST_MODE").is_ok(),
            fail_on_missing: true,
        }
    }
}

/// Collect all secret values from configuration
///
/// # Arguments
/// * `secrets` - HashMap of secret names to their configuration
/// * `ctx` - Context for path expansion
/// * `config` - Configuration for secret handling
///
/// # Returns
/// HashMap of secret names to their resolved values, or an error
pub fn collect_secrets(
    secrets: &HashMap<String, SecretValue>,
    ctx: &EnvContext,
    config: &SecretsConfig,
) -> Result<HashMap<String, String>, SecretError> {
    let mut result = HashMap::new();

    for (name, secret_config) in secrets {
        match resolve_secret(name, secret_config, ctx, config) {
            Ok(Some(value)) => {
                result.insert(name.clone(), value);
            }
            Ok(None) => {
                // Optional secret not provided, skip
            }
            Err(e) => {
                if config.fail_on_missing {
                    return Err(e);
                }
                eprintln!("Warning: Could not resolve secret '{}': {}", name, e);
            }
        }
    }

    Ok(result)
}

#[cfg(test)]
#[cfg(unix)]
mod permissive_perms_tests {
    //! Verifies the structured-warning behavior for secret files with
    //! permissive permissions. The previous `eprintln!` path was not testable.

    use super::*;
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;

    fn make_secret_file(mode: u32) -> tempfile::NamedTempFile {
        let mut tmp = tempfile::NamedTempFile::new().expect("tempfile");
        write!(tmp, "supersecret").unwrap();
        let mut perms = tmp.as_file().metadata().unwrap().permissions();
        perms.set_mode(mode);
        std::fs::set_permissions(tmp.path(), perms).unwrap();
        tmp
    }

    fn build_ctx() -> EnvContext {
        EnvContext::new()
    }

    #[test]
    fn resolve_secret_with_0600_does_not_warn_about_perms() {
        let tmp = make_secret_file(0o600);
        let secret = SecretValue::FromFile {
            from_file: tmp.path().to_string_lossy().to_string(),
        };
        let ctx = build_ctx();
        let result = resolve_secret("TEST_SECRET", &secret, &ctx, &SecretsConfig::default());
        assert_eq!(result.unwrap(), Some("supersecret".to_string()));
    }

    #[test]
    fn resolve_secret_with_0644_still_returns_value() {
        // Behavior today: warn but return. Documents the contract; tighten
        // to `Err` once we ship a strict-secrets toggle.
        let tmp = make_secret_file(0o644);
        let secret = SecretValue::FromFile {
            from_file: tmp.path().to_string_lossy().to_string(),
        };
        let ctx = build_ctx();
        let result = resolve_secret("TEST_SECRET", &secret, &ctx, &SecretsConfig::default());
        assert_eq!(result.unwrap(), Some("supersecret".to_string()));
    }
}

/// Resolve a single secret value
fn resolve_secret(
    name: &str,
    config: &SecretValue,
    ctx: &EnvContext,
    secrets_config: &SecretsConfig,
) -> Result<Option<String>, SecretError> {
    match config {
        SecretValue::FromFile { from_file } => {
            let path = expand_path(from_file, ctx);
            if !path.exists() {
                return Err(SecretError::FileNotFound(path.display().to_string()));
            }
            // Warn if secret file has overly permissive permissions.
            // Path emitted through redact_path so home-dir prefixes don't end up
            // in shared ticket bundles.
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Ok(metadata) = fs::metadata(&path) {
                    let mode = metadata.permissions().mode();
                    if mode & 0o077 != 0 {
                        let safe_path = crate::network::redact_home(&path.display().to_string());
                        tracing::warn!(
                            event = "secret.permissive_perms",
                            path = %safe_path,
                            mode = format!("{:o}", mode & 0o777),
                            secret_name = %name,
                            "secret file has permissive permissions; chmod 600 recommended"
                        );
                    }
                }
            }
            let content = fs::read_to_string(&path)?;
            Ok(Some(content.trim().to_string()))
        }
        SecretValue::Prompt {
            env,
            required,
            description,
        } => {
            // First check environment variable if specified
            if let Some(env_var) = env {
                if let Ok(value) = std::env::var(env_var) {
                    if !value.is_empty() {
                        return Ok(Some(value));
                    }
                }
            }

            // Check if the secret itself is in environment
            if let Ok(value) = std::env::var(name) {
                if !value.is_empty() {
                    return Ok(Some(value));
                }
            }

            // In CI mode, don't prompt
            if secrets_config.ci_mode {
                if *required {
                    return Err(SecretError::MissingRequired(name.to_string()));
                }
                return Ok(None);
            }

            // Prompt user for input
            prompt_secret(name, description.as_deref(), *required)
        }
        SecretValue::Simple(marker) => {
            // Simple marker - check environment first
            if let Ok(value) = std::env::var(name) {
                if !value.is_empty() {
                    return Ok(Some(value));
                }
            }

            // Check the marker value as an env var too
            if marker != name {
                if let Ok(value) = std::env::var(marker) {
                    if !value.is_empty() {
                        return Ok(Some(value));
                    }
                }
            }

            // In CI mode, skip prompting
            if secrets_config.ci_mode {
                return Err(SecretError::MissingRequired(name.to_string()));
            }

            // Prompt for the secret
            prompt_secret(name, None, true)
        }
    }
}

/// Prompt user for a secret with hidden input
fn prompt_secret(
    name: &str,
    description: Option<&str>,
    required: bool,
) -> Result<Option<String>, SecretError> {
    // Print prompt
    if let Some(desc) = description {
        println!("{} ({})", name, desc);
    }

    print!("Enter value for {}: ", name);
    io::stdout().flush()?;

    // Read password with hidden input
    let password = rpassword::read_password().map_err(|_| SecretError::InputError)?;

    if password.is_empty() {
        if required {
            Err(SecretError::MissingRequired(name.to_string()))
        } else {
            Ok(None)
        }
    } else {
        Ok(Some(password))
    }
}

/// Load a secret from a file path
#[allow(dead_code)] // Public API for secret loading
pub fn load_secret_from_file(path: &Path) -> Result<String, SecretError> {
    if !path.exists() {
        return Err(SecretError::FileNotFound(path.display().to_string()));
    }
    let content = fs::read_to_string(path)?;
    Ok(content.trim().to_string())
}

/// Preview secrets that would be collected (for dry-run)
/// Returns secret names without actual values
#[allow(dead_code)] // Public API for dry-run secret preview
pub fn preview_secrets(secrets: &HashMap<String, SecretValue>) -> Vec<String> {
    secrets.keys().cloned().collect()
}

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

    #[test]
    fn test_load_secret_from_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("secret.txt");
        fs::write(&file_path, "my_secret_value\n").unwrap();

        let result = load_secret_from_file(&file_path).unwrap();
        assert_eq!(result, "my_secret_value");
    }

    #[test]
    fn test_load_secret_from_file_not_found() {
        let result = load_secret_from_file(Path::new("/nonexistent/path/secret.txt"));
        assert!(matches!(result, Err(SecretError::FileNotFound(_))));
    }

    #[test]
    #[allow(unsafe_code)]
    fn test_secrets_config_default_ci_detection() {
        // Save current env
        let ci_was_set = std::env::var("CI").is_ok();

        // Set CI env to test detection
        // SAFETY: Test environment, single-threaded access
        unsafe {
            std::env::set_var("JARVY_TEST_MODE", "1");
        }
        let config = SecretsConfig::default();
        assert!(config.ci_mode);

        // Clean up if CI wasn't originally set
        if !ci_was_set {
            // SAFETY: Test environment, single-threaded access
            unsafe {
                std::env::remove_var("CI");
            }
        }
    }

    #[test]
    fn test_resolve_secret_from_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("secret.txt");
        fs::write(&file_path, "file_secret_value").unwrap();

        let ctx = EnvContext::new();
        let config = SecretsConfig {
            ci_mode: true,
            fail_on_missing: true,
        };

        let secret_config = SecretValue::FromFile {
            from_file: file_path.to_string_lossy().to_string(),
        };

        let result = resolve_secret("TEST_SECRET", &secret_config, &ctx, &config).unwrap();
        assert_eq!(result, Some("file_secret_value".to_string()));
    }

    #[test]
    #[allow(unsafe_code)]
    fn test_resolve_secret_from_env() {
        // SAFETY: Test environment, single-threaded access
        unsafe {
            std::env::set_var("TEST_SECRET_ENV", "env_value");
        }

        let ctx = EnvContext::new();
        let config = SecretsConfig {
            ci_mode: true,
            fail_on_missing: true,
        };

        let secret_config = SecretValue::Prompt {
            env: Some("TEST_SECRET_ENV".to_string()),
            required: true,
            description: None,
        };

        let result = resolve_secret("MY_SECRET", &secret_config, &ctx, &config).unwrap();
        assert_eq!(result, Some("env_value".to_string()));

        // SAFETY: Test environment, single-threaded access
        unsafe {
            std::env::remove_var("TEST_SECRET_ENV");
        }
    }

    #[test]
    fn test_resolve_secret_ci_mode_required() {
        let ctx = EnvContext::new();
        let config = SecretsConfig {
            ci_mode: true,
            fail_on_missing: true,
        };

        let secret_config = SecretValue::Prompt {
            env: None,
            required: true,
            description: None,
        };

        let result = resolve_secret("MISSING_SECRET", &secret_config, &ctx, &config);
        assert!(matches!(result, Err(SecretError::MissingRequired(_))));
    }

    #[test]
    fn test_resolve_secret_ci_mode_optional() {
        let ctx = EnvContext::new();
        let config = SecretsConfig {
            ci_mode: true,
            fail_on_missing: true,
        };

        let secret_config = SecretValue::Prompt {
            env: None,
            required: false,
            description: None,
        };

        let result = resolve_secret("OPTIONAL_SECRET", &secret_config, &ctx, &config).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_preview_secrets() {
        let mut secrets = HashMap::new();
        secrets.insert("SECRET_A".to_string(), SecretValue::Simple("a".to_string()));
        secrets.insert("SECRET_B".to_string(), SecretValue::Simple("b".to_string()));

        let preview = preview_secrets(&secrets);
        assert_eq!(preview.len(), 2);
        assert!(preview.contains(&"SECRET_A".to_string()));
        assert!(preview.contains(&"SECRET_B".to_string()));
    }

    #[test]
    fn test_collect_secrets_from_files() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("secret.txt");
        fs::write(&file_path, "collected_secret").unwrap();

        let mut secrets = HashMap::new();
        secrets.insert(
            "FILE_SECRET".to_string(),
            SecretValue::FromFile {
                from_file: file_path.to_string_lossy().to_string(),
            },
        );

        let ctx = EnvContext::new();
        let config = SecretsConfig {
            ci_mode: true,
            fail_on_missing: true,
        };

        let result = collect_secrets(&secrets, &ctx, &config).unwrap();
        assert_eq!(
            result.get("FILE_SECRET"),
            Some(&"collected_secret".to_string())
        );
    }
}