vivo 0.11.2

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};

use super::RemoteBackend;

pub struct RustfsBackend {
    pub(crate) endpoint: String,
    pub(crate) bucket: String,
    pub(super) subpath: String,
    pub(crate) mc_max_workers: Option<u32>,
    pub(crate) mc_limit_upload: Option<String>,
}

pub(super) enum SyncTool {
    Mc,
    Aws,
    Rclone,
}

pub(super) fn is_bucket_already_exists_error(stderr: &str) -> bool {
    stderr.contains("BucketAlreadyOwnedByYou") || stderr.contains("BucketAlreadyExists")
}

pub(super) fn detect_tool() -> Result<(SyncTool, Option<&'static str>), String> {
    if Command::new("mc")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        return Ok((SyncTool::Mc, None));
    }
    if Command::new("aws")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        return Ok((SyncTool::Aws, Some("mc not found — using aws (install mc from https://min.io/docs/minio/linux/reference/minio-mc.html for best rustfs compatibility)")));
    }
    if Command::new("rclone")
        .arg("version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        return Ok((SyncTool::Rclone, Some("mc not found — using rclone (install mc from https://min.io/docs/minio/linux/reference/minio-mc.html for best rustfs compatibility)")));
    }
    Err(
        "no sync tool found — install mc (https://min.io/docs/minio/linux/reference/minio-mc.html), \
         aws CLI (https://aws.amazon.com/cli/), or rclone (https://rclone.org)"
            .to_string(),
    )
}

pub(crate) fn percent_encode_credential(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '+' => out.push_str("%2B"),
            '/' => out.push_str("%2F"),
            '=' => out.push_str("%3D"),
            ':' => out.push_str("%3A"),
            '@' => out.push_str("%40"),
            '#' => out.push_str("%23"),
            '?' => out.push_str("%3F"),
            '&' => out.push_str("%26"),
            '%' => out.push_str("%25"),
            _ => out.push(c),
        }
    }
    out
}

impl RustfsBackend {
    fn s3_dest(&self) -> String {
        if self.subpath.is_empty() {
            format!("s3://{}", self.bucket)
        } else {
            format!("s3://{}/{}", self.bucket, self.subpath)
        }
    }

    fn rclone_dest(&self) -> String {
        if self.subpath.is_empty() {
            format!(":s3:{}", self.bucket)
        } else {
            format!(":s3:{}/{}", self.bucket, self.subpath)
        }
    }

    fn mc_dest(&self) -> String {
        if self.subpath.is_empty() {
            format!("vivo-sync/{}", self.bucket)
        } else {
            format!("vivo-sync/{}/{}", self.bucket, self.subpath)
        }
    }

    fn ensure_bucket_mc(&self, mc_env: &HashMap<String, String>) -> Result<(), String> {
        let dest = format!("vivo-sync/{}", self.bucket);
        self.run_sync_command("mc", &["mb", "--ignore-existing", &dest], mc_env)
    }

    fn ensure_bucket_aws(&self, env: &HashMap<String, String>) -> Result<(), String> {
        let output = Command::new("aws")
            .args(["s3", "mb", &format!("s3://{}", self.bucket), "--endpoint-url", &self.endpoint])
            .envs(env)
            .output()
            .map_err(|e| format!("failed to run aws s3 mb: {e}"))?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if !is_bucket_already_exists_error(&stderr) {
                return Err(format!("aws s3 mb failed for bucket '{}': {stderr}", self.bucket));
            }
        }
        Ok(())
    }

    fn ensure_bucket_rclone(&self, rclone_env: &HashMap<String, String>) -> Result<(), String> {
        let dest = format!(":s3:{}", self.bucket);
        self.run_sync_command(
            "rclone",
            &["mkdir", &dest, "--s3-provider", "Other", "--s3-endpoint", &self.endpoint],
            rclone_env,
        )
    }

    fn run_sync_command(
        &self,
        cmd_name: &str,
        args: &[&str],
        env: &HashMap<String, String>,
    ) -> Result<(), String> {
        let mut child = Command::new(cmd_name)
            .args(args)
            .envs(env)
            .stdout(Stdio::inherit())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| format!("failed to run {cmd_name}: {e}"))?;

        let stderr_reader = BufReader::new(child.stderr.take().unwrap());
        let stderr_thread = std::thread::spawn(move || {
            let mut collected = String::new();
            for line in stderr_reader.lines().map_while(Result::ok) {
                eprintln!("{line}");
                collected.push_str(&line);
                collected.push('\n');
            }
            collected
        });

        let status = child
            .wait()
            .map_err(|e| format!("failed to wait for {cmd_name}: {e}"))?;
        let stderr = stderr_thread.join().unwrap_or_default();

        if !status.success() {
            return Err(format!("{cmd_name} sync to {} failed: {stderr}", self.endpoint));
        }
        Ok(())
    }

    fn mc_mirror_args(&self) -> Vec<String> {
        let mut extra = Vec::new();
        if let Some(p) = self.mc_max_workers {
            extra.push("--max-workers".to_string());
            extra.push(p.to_string());
        }
        if let Some(ref limit) = self.mc_limit_upload {
            extra.push("--limit-upload".to_string());
            extra.push(limit.clone());
        }
        extra
    }

    fn sync_mc(&self, local_repo: &str, env: &HashMap<String, String>) -> Result<(), String> {
        let key = env.get("AWS_ACCESS_KEY_ID").map(String::as_str).unwrap_or("");
        let secret = env.get("AWS_SECRET_ACCESS_KEY").map(String::as_str).unwrap_or("");

        // Build MC_HOST_vivo-sync URL — credentials percent-encoded to avoid argv exposure
        // and handle special chars in base64-like secret keys
        let (scheme, host) = self.endpoint.split_once("://").unwrap_or(("https", &self.endpoint));
        let mc_host = format!("{}://{}:{}@{}", scheme, percent_encode_credential(key), percent_encode_credential(secret), host);

        let dest = self.mc_dest();
        let mut mc_env = HashMap::new();
        mc_env.insert("MC_HOST_vivo-sync".to_string(), mc_host);

        self.ensure_bucket_mc(&mc_env)?;

        let extra = self.mc_mirror_args();
        let mut args = vec!["mirror", "--remove", "--overwrite"];
        let extra_str: Vec<&str> = extra.iter().map(String::as_str).collect();
        args.extend_from_slice(&extra_str);
        args.push(local_repo);
        args.push(&dest);

        self.run_sync_command("mc", &args, &mc_env)
    }

    fn sync_aws(&self, local_repo: &str, env: &HashMap<String, String>) -> Result<(), String> {
        self.ensure_bucket_aws(env)?;
        let dest = self.s3_dest();
        self.run_sync_command(
            "aws",
            &["s3", "sync", "--delete", "--size-only", local_repo, &dest, "--endpoint-url", &self.endpoint],
            env,
        )
    }

    fn sync_rclone(&self, local_repo: &str, env: &HashMap<String, String>) -> Result<(), String> {
        let dest = self.rclone_dest();
        let key = env.get("AWS_ACCESS_KEY_ID").cloned().unwrap_or_default();
        let secret = env.get("AWS_SECRET_ACCESS_KEY").cloned().unwrap_or_default();

        let mut rclone_env = HashMap::new();
        rclone_env.insert("RCLONE_S3_ACCESS_KEY_ID".to_string(), key);
        rclone_env.insert("RCLONE_S3_SECRET_ACCESS_KEY".to_string(), secret);

        self.ensure_bucket_rclone(&rclone_env)?;
        self.run_sync_command(
            "rclone",
            &[
                "sync", "--delete-during", "--size-only",
                local_repo, &dest,
                "--s3-provider", "Other",
                "--s3-endpoint", &self.endpoint,
            ],
            &rclone_env,
        )
    }

    pub fn from_url(url: &str) -> Result<Self, String> {
        if !url.starts_with("rustfs:") {
            return Err(format!("not a rustfs URL: '{url}'"));
        }

        // Strip the "rustfs:" prefix to get the inner URL (e.g. "https://host/bucket")
        let inner = &url["rustfs:".len()..];

        // Require a scheme with "://"
        let scheme_sep = inner
            .find("://")
            .ok_or_else(|| format!("rustfs URL missing scheme (expected https:// or http://): '{url}'"))?;
        let after_scheme = &inner[scheme_sep + 3..];

        // Find the first '/' after the host (which separates host from path)
        let slash_pos = after_scheme
            .find('/')
            .ok_or_else(|| format!("rustfs URL missing bucket (no path after host): '{url}'"))?;

        let endpoint = inner[..scheme_sep + 3 + slash_pos].to_string();

        // Everything after the slash is the path: "bucket" or "bucket/subpath"
        let path = &after_scheme[slash_pos + 1..];

        if path.is_empty() {
            return Err(format!("rustfs URL missing bucket (empty path): '{url}'"));
        }

        let (bucket, subpath) = match path.find('/') {
            Some(pos) => (path[..pos].to_string(), path[pos + 1..].to_string()),
            None => (path.to_string(), String::new()),
        };

        if bucket.is_empty() {
            return Err(format!("rustfs URL missing bucket (empty bucket): '{url}'"));
        }

        Ok(RustfsBackend { endpoint, bucket, subpath, mc_max_workers: None, mc_limit_upload: None })
    }

    pub fn from_remote(remote: &crate::backup_config::backup::Remote) -> Result<Self, String> {
        let mut backend = Self::from_url(&remote.url)?;
        backend.mc_max_workers = remote.mc_max_workers;
        backend.mc_limit_upload = remote.mc_limit_upload.clone();
        Ok(backend)
    }
}

impl RemoteBackend for RustfsBackend {
    fn name(&self) -> &str {
        "rustfs"
    }

    fn check_installed(&self) -> Result<(), String> {
        detect_tool().map(|_| ())
    }

    fn sync(
        &self,
        local_repo: &str,
        dry_run: bool,
        env: &HashMap<String, String>,
    ) -> Result<(), String> {
        if dry_run {
            println!(
                "[dry-run] would sync {} to rustfs:{}/{}",
                local_repo, self.endpoint, self.bucket
            );
            return Ok(());
        }

        super::verify_restic_repo(local_repo)?;

        let (tool, warning) = detect_tool()?;
        if let Some(msg) = warning {
            eprintln!("[warn] {msg}");
        }

        match tool {
            SyncTool::Mc => self.sync_mc(local_repo, env),
            SyncTool::Aws => self.sync_aws(local_repo, env),
            SyncTool::Rclone => self.sync_rclone(local_repo, env),
        }
    }
}

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

    #[test]
    fn parses_https_url() {
        let b = RustfsBackend::from_url("rustfs:https://rustfs.cinnamon-trout.ts.net/filecabinet").unwrap();
        assert_eq!(b.endpoint, "https://rustfs.cinnamon-trout.ts.net");
        assert_eq!(b.bucket, "filecabinet");
        assert_eq!(b.subpath, "");
    }

    #[test]
    fn parses_http_with_port() {
        let b = RustfsBackend::from_url("rustfs:http://nas:9000/backup").unwrap();
        assert_eq!(b.endpoint, "http://nas:9000");
        assert_eq!(b.bucket, "backup");
        assert_eq!(b.subpath, "");
    }

    #[test]
    fn parses_url_with_subpath() {
        let b = RustfsBackend::from_url("rustfs:http://nas:9000/bucket/restic/repo").unwrap();
        assert_eq!(b.endpoint, "http://nas:9000");
        assert_eq!(b.bucket, "bucket");
        assert_eq!(b.subpath, "restic/repo");
    }

    #[test]
    fn rejects_missing_bucket() {
        assert!(RustfsBackend::from_url("rustfs:https://host/").is_err());
    }

    #[test]
    fn rejects_missing_scheme() {
        assert!(RustfsBackend::from_url("rustfs:host/bucket").is_err());
    }

    #[test]
    fn rejects_non_rustfs_prefix() {
        assert!(RustfsBackend::from_url("s3:http://host/bucket").is_err());
    }

    #[test]
    fn name_returns_rustfs() {
        let b = RustfsBackend::from_url("rustfs:https://host/bucket").unwrap();
        assert_eq!(b.name(), "rustfs");
    }

    #[test]
    fn dry_run_returns_ok_without_tools() {
        let b = RustfsBackend::from_url("rustfs:https://host/bucket").unwrap();
        let result = b.sync("/tmp/repo", true, &HashMap::new());
        assert!(result.is_ok());
    }

    #[test]
    fn is_bucket_already_exists_tolerates_owned_by_you() {
        assert!(is_bucket_already_exists_error("BucketAlreadyOwnedByYou"));
    }

    #[test]
    fn is_bucket_already_exists_tolerates_already_exists() {
        assert!(is_bucket_already_exists_error("make_bucket_failed: BucketAlreadyExists"));
    }

    #[test]
    fn is_bucket_already_exists_rejects_other_errors() {
        assert!(!is_bucket_already_exists_error("AccessDenied: permission denied"));
    }

    #[test]
    fn is_bucket_already_exists_rejects_empty() {
        assert!(!is_bucket_already_exists_error(""));
    }

    #[test]
    fn check_installed_fails_when_no_tools_on_path() {
        let b = RustfsBackend::from_url("rustfs:https://host/bucket").unwrap();
        let original_path = std::env::var("PATH").unwrap_or_default();
        std::env::set_var("PATH", "");
        let result = b.check_installed();
        std::env::set_var("PATH", &original_path);
        assert!(result.is_err());
        let msg = result.unwrap_err();
        assert!(msg.contains("mc") && msg.contains("aws") && msg.contains("rclone"));
    }

    #[test]
    fn mc_mirror_args_empty_when_no_options() {
        let b = RustfsBackend::from_url("rustfs:https://host/bucket").unwrap();
        assert!(b.mc_mirror_args().is_empty());
    }

    #[test]
    fn mc_mirror_args_parallel_only() {
        let b = RustfsBackend {
            endpoint: "https://host".to_string(),
            bucket: "bucket".to_string(),
            subpath: String::new(),
            mc_max_workers: Some(4),
            mc_limit_upload: None,
        };
        let args = b.mc_mirror_args();
        assert_eq!(args, vec!["--max-workers", "4"]);
    }

    #[test]
    fn mc_mirror_args_limit_upload_only() {
        let b = RustfsBackend {
            endpoint: "https://host".to_string(),
            bucket: "bucket".to_string(),
            subpath: String::new(),
            mc_max_workers: None,
            mc_limit_upload: Some("5MiB".to_string()),
        };
        let args = b.mc_mirror_args();
        assert_eq!(args, vec!["--limit-upload", "5MiB"]);
    }

    #[test]
    fn mc_mirror_args_both_options() {
        let b = RustfsBackend {
            endpoint: "https://host".to_string(),
            bucket: "bucket".to_string(),
            subpath: String::new(),
            mc_max_workers: Some(2),
            mc_limit_upload: Some("10MiB".to_string()),
        };
        let args = b.mc_mirror_args();
        assert_eq!(args, vec!["--max-workers", "2", "--limit-upload", "10MiB"]);
    }

    #[test]
    fn from_url_sets_mc_fields_to_none() {
        let b = RustfsBackend::from_url("rustfs:https://host/bucket").unwrap();
        assert!(b.mc_max_workers.is_none());
        assert!(b.mc_limit_upload.is_none());
    }
}