vivo 0.9.0

restic backup orchestrator with multi-remote sync and SOPS-encrypted secrets
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
444
445
446
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use std::{env, fs, process};

use crate::backup_config::{decrypt_sops_file, parse_secrets, BackupConfig};
use crate::config::{xdg_config_home, Secrets};

pub enum CheckStatus {
    Ok,
    Warn,
    Fail,
}

pub struct CheckResult {
    pub label: String,
    pub status: CheckStatus,
    pub detail: Option<String>,
}

pub fn print_result(r: &CheckResult) {
    let tag = match r.status {
        CheckStatus::Ok   => "  [ok]  ",
        CheckStatus::Warn => "  [warn]",
        CheckStatus::Fail => "  [fail]",
    };
    match &r.detail {
        Some(d) => println!("{tag} {}{d}", r.label),
        None    => println!("{tag} {}", r.label),
    }
}

pub fn tool_version(name: &str, version_flag: &str) -> Option<String> {
    process::Command::new(name)
        .arg(version_flag)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            String::from_utf8(o.stdout)
                .ok()
                .and_then(|s| s.lines().next().map(str::to_string))
        })
}

pub fn check_tool_present(name: &str, version_flag: &str, install_hint: &str) -> CheckResult {
    match tool_version(name, version_flag) {
        Some(v) => CheckResult {
            label: format!("{name} ({v})"),
            status: CheckStatus::Ok,
            detail: None,
        },
        None => CheckResult {
            label: name.to_string(),
            status: CheckStatus::Fail,
            detail: Some(install_hint.to_string()),
        },
    }
}

pub fn check_age_key() -> CheckResult {
    let path = if let Ok(p) = env::var("SOPS_AGE_KEY_FILE") {
        p
    } else {
        xdg_config_home()
            .join("sops/age/keys.txt")
            .to_string_lossy()
            .into_owned()
    };
    if Path::new(&path).exists() {
        CheckResult {
            label: format!("age key ({path})"),
            status: CheckStatus::Ok,
            detail: None,
        }
    } else {
        CheckResult {
            label: "age key".to_string(),
            status: CheckStatus::Fail,
            detail: Some(format!(
                "not found at {path} — run: age-keygen -o {path}"
            )),
        }
    }
}

pub fn check_config(config_path: &str) -> CheckResult {
    let label = format!("config ({config_path})");
    match fs::read_to_string(config_path) {
        Err(e) => CheckResult {
            label,
            status: CheckStatus::Fail,
            detail: Some(format!("{e} — run `vivo config init`")),
        },
        Ok(content) => match knuffel::parse::<BackupConfig>(config_path, &content) {
            Err(e) => CheckResult {
                label,
                status: CheckStatus::Fail,
                detail: Some(e.to_string()),
            },
            Ok(_) => CheckResult {
                label,
                status: CheckStatus::Ok,
                detail: None,
            },
        },
    }
}

pub fn check_secrets(secrets_path: &str) -> Option<Secrets> {
    decrypt_sops_file(secrets_path)
        .ok()
        .and_then(|yaml| parse_secrets(&yaml).ok())
}

pub fn check_secrets_present(secrets_path: &str) -> CheckResult {
    let label = format!("secrets ({secrets_path})");
    match decrypt_sops_file(secrets_path) {
        Err(e) => CheckResult {
            label,
            status: CheckStatus::Fail,
            detail: Some(format!("{e} — run `vivo secrets init`")),
        },
        Ok(yaml) => match parse_secrets(&yaml) {
            Err(e) => CheckResult {
                label,
                status: CheckStatus::Fail,
                detail: Some(format!("parse error: {e}")),
            },
            Ok(_) => CheckResult {
                label,
                status: CheckStatus::Ok,
                detail: None,
            },
        },
    }
}

pub fn check_restic_password(secrets: &Secrets) -> CheckResult {
    if secrets.restic_password.is_empty() || secrets.restic_password == "change-me" {
        CheckResult {
            label: "restic_password".to_string(),
            status: CheckStatus::Fail,
            detail: Some("not set — run `vivo secrets edit`".to_string()),
        }
    } else {
        CheckResult {
            label: "restic_password".to_string(),
            status: CheckStatus::Ok,
            detail: None,
        }
    }
}

pub(crate) fn run_with_timeout(cmd: &mut process::Command, timeout: Duration) -> Result<bool, String> {
    let mut child = cmd.spawn().map_err(|e| e.to_string())?;
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            return Ok(false);
        }
        match child.try_wait().map_err(|e| e.to_string())? {
            Some(s) => return Ok(s.success()),
            None => std::thread::sleep(Duration::from_millis(100)),
        }
    }
}

pub fn check_remote_connectivity(
    url: &str,
    creds_name: &str,
    credentials: &HashMap<String, HashMap<String, String>>,
    restic_password: &str,
) -> CheckResult {
    let label = format!("remote {url}");
    let creds = match credentials.get(creds_name) {
        None => {
            return CheckResult {
                label,
                status: CheckStatus::Warn,
                detail: Some(format!("credentials profile '{creds_name}' not in secrets")),
            }
        }
        Some(c) => c,
    };

    let timeout = Duration::from_secs(15);

    if url.starts_with("b2:") {
        let bucket = url.strip_prefix("b2:").unwrap_or("").split(':').next().unwrap_or("");
        let mut cmd = process::Command::new("b2");
        cmd.args(["ls", bucket])
            .envs(creds)
            .stdout(process::Stdio::null())
            .stderr(process::Stdio::null());
        match run_with_timeout(&mut cmd, timeout) {
            Ok(true) => CheckResult { label, status: CheckStatus::Ok, detail: None },
            Ok(false) => CheckResult {
                label,
                status: CheckStatus::Warn,
                detail: Some("connection timed out or failed — check B2 credentials".to_string()),
            },
            Err(e) => CheckResult { label, status: CheckStatus::Warn, detail: Some(e) },
        }
    } else if url.starts_with("s3:") {
        let mut cmd = process::Command::new("restic");
        cmd.args(["snapshots", "--repo", url, "--no-lock"])
            .envs(creds)
            .env("RESTIC_PASSWORD", restic_password)
            .stdout(process::Stdio::null())
            .stderr(process::Stdio::null());
        match run_with_timeout(&mut cmd, timeout) {
            Ok(true) => CheckResult { label, status: CheckStatus::Ok, detail: None },
            Ok(false) => CheckResult {
                label,
                status: CheckStatus::Warn,
                detail: Some("connection timed out or failed — check S3 credentials and repo init".to_string()),
            },
            Err(e) => CheckResult { label, status: CheckStatus::Warn, detail: Some(e) },
        }
    } else {
        CheckResult {
            label,
            status: CheckStatus::Warn,
            detail: Some("unsupported remote prefix — skipping connectivity check".to_string()),
        }
    }
}

#[cfg(target_os = "linux")]
pub fn check_fuse() -> CheckResult {
    let found = ["fusermount", "fusermount3"].iter().any(|bin| {
        process::Command::new(bin)
            .arg("--version")
            .stdout(process::Stdio::null())
            .stderr(process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    });
    if found {
        CheckResult {
            label: "FUSE (fusermount)".to_string(),
            status: CheckStatus::Ok,
            detail: None,
        }
    } else {
        CheckResult {
            label: "FUSE (fusermount)".to_string(),
            status: CheckStatus::Fail,
            detail: Some(
                "fusermount not found — install FUSE: sudo apt install fuse  OR  sudo dnf install fuse"
                    .to_string(),
            ),
        }
    }
}

#[cfg(target_os = "macos")]
pub fn check_fuse() -> CheckResult {
    let has_mount = process::Command::new("mount_macfuse")
        .arg("--version")
        .stdout(process::Stdio::null())
        .stderr(process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    let kext_exists = std::path::Path::new("/Library/Filesystems/macfuse.kext").exists();
    if has_mount || kext_exists {
        CheckResult {
            label: "FUSE (macFUSE)".to_string(),
            status: CheckStatus::Ok,
            detail: None,
        }
    } else {
        CheckResult {
            label: "FUSE (macFUSE)".to_string(),
            status: CheckStatus::Fail,
            detail: Some("macFUSE not found — install: brew install --cask macfuse".to_string()),
        }
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn check_fuse() -> CheckResult {
    CheckResult {
        label: "FUSE".to_string(),
        status: CheckStatus::Fail,
        detail: Some("FUSE mount is not supported on this platform".to_string()),
    }
}

pub fn run_doctor(config_path: &str, secrets_path: &str) -> i32 {
    let mut results: Vec<CheckResult> = Vec::new();
    let mut required_failures = 0u32;
    let mut warnings = 0u32;

    let restic = check_tool_present("restic", "version", "install from https://restic.net");
    let sops   = check_tool_present("sops", "--version", "install from https://github.com/getsops/sops");
    let age    = check_age_key();
    let config = check_config(config_path);
    let secrets_result = check_secrets_present(secrets_path);

    for r in [&restic, &sops, &age, &config, &secrets_result] {
        if matches!(r.status, CheckStatus::Fail) {
            required_failures += 1;
        }
    }

    results.push(restic);
    results.push(sops);
    results.push(age);
    results.push(config);
    results.push(secrets_result);

    let maybe_secrets = check_secrets(secrets_path);
    if let Some(ref s) = maybe_secrets {
        let pw = check_restic_password(s);
        if matches!(pw.status, CheckStatus::Fail) {
            required_failures += 1;
        }
        results.push(pw);
    }

    if let (Ok(content), Some(ref secrets)) = (fs::read_to_string(config_path), maybe_secrets) {
        if let Ok(backup_config) = knuffel::parse::<BackupConfig>(config_path, &content) {
            for (url, creds_name) in backup_config.all_remotes() {
                let r = check_remote_connectivity(
                    url,
                    creds_name,
                    &secrets.credentials,
                    &secrets.restic_password,
                );
                if matches!(r.status, CheckStatus::Warn) {
                    warnings += 1;
                }
                results.push(r);
            }
        }
    }

    for r in &results {
        print_result(r);
    }

    println!();
    match (required_failures, warnings) {
        (0, 0) => println!("All checks passed."),
        (0, w) => println!("{w} warning(s). Run `vivo doctor` again after resolving."),
        (f, 0) => println!("{f} required check(s) failed. Fix the issues above and re-run `vivo doctor`."),
        (f, w) => println!("{f} required check(s) failed, {w} warning(s). Fix required checks first."),
    }

    if required_failures > 0 { 1 } else { 0 }
}

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

    #[test]
    fn check_tool_present_fails_for_nonexistent() {
        let r = check_tool_present("__no_such_tool_xyz__", "--version", "hint");
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_age_key_fails_when_missing() {
        env::set_var("SOPS_AGE_KEY_FILE", "/tmp/__vivo_test_no_such_key__.txt");
        let r = check_age_key();
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_age_key_ok_when_file_exists() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        env::set_var("SOPS_AGE_KEY_FILE", tmp.path().to_str().unwrap());
        let r = check_age_key();
        assert!(matches!(r.status, CheckStatus::Ok));
    }

    #[test]
    fn check_config_fails_for_missing_file() {
        let r = check_config("/tmp/__vivo_no_such_config__.kdl");
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_config_fails_for_invalid_kdl() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        writeln!(f, "this is not valid kdl {{{{").unwrap();
        let r = check_config(f.path().to_str().unwrap());
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_config_ok_for_valid_kdl() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        writeln!(f, r#"default-task "backup"
tasks {{
    task "backup" {{
        command "echo hi"
    }}
}}"#).unwrap();
        let r = check_config(f.path().to_str().unwrap());
        assert!(matches!(r.status, CheckStatus::Ok));
    }

    #[test]
    fn check_restic_password_fails_for_placeholder() {
        let secrets = Secrets {
            restic_password: "change-me".to_string(),
            credentials: HashMap::new(),
        };
        let r = check_restic_password(&secrets);
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_restic_password_ok_for_real_password() {
        let secrets = Secrets {
            restic_password: "hunter2".to_string(),
            credentials: HashMap::new(),
        };
        let r = check_restic_password(&secrets);
        assert!(matches!(r.status, CheckStatus::Ok));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn check_fuse_fails_when_path_is_empty() {
        let original = std::env::var("PATH").unwrap_or_default();
        std::env::set_var("PATH", "");
        let r = check_fuse();
        std::env::set_var("PATH", &original);
        assert!(matches!(r.status, CheckStatus::Fail));
    }

    #[test]
    fn check_fuse_returns_a_result() {
        // Should not panic regardless of platform
        let _ = check_fuse();
    }
}